2012-05-08 65 views
0

我想在應用程序啓動的某個區域放置一些圖像。 由於圖像的數量不是固定的數量,所以我必須動態地創建圖像。 我想設置每張圖片的位置/邊距,以創造良好的平衡。Android。如何在創建時移動圖像視圖(設置位置/邊距)

我試過了,但沒有效果。 ·創建後,使用imageview.layout()。 ·使用LayoutParams.margins()。 ·使用AsyncTask設置邊距。 ·activity.runOnUiThread()。

這是代碼:

// After access server, if needed then add a imageview to the 'c_box' 
    // c_box: the parent that imageview to add. 
    FrameLayout c_box = (FrameLayout) findViewById(R.id.c_box); 

    MarginLayoutParams mlp = new MarginLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 

    ImageView img1 = new ImageView(this); 
    img1.setImageResource(R.drawable.c_file); 
    img1.setLayoutParams(params); 
    img1.setLongClickable(true); 
    img1.setId(img_id); 
    c_box.addView(img1); 

    img1.setOnTouchListener(listener); 


    **// it's possible to set the position by layout or margin? 
    img1.layout(100, 100, 200, 200);** 

我不知道在哪裏調用無效()方法。


// After access server, if needed then add a imageview to the 'c_box' 
    // c_box: the parent that imageview to add. 
    FrameLayout c_box = (FrameLayout) findViewById(R.id.c_box); 

    MarginLayoutParams mlp = new MarginLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
    mlp.setMargins(100, 100, 200, 200); 
    ImageView img1 = new ImageView(this); 
    img1.setImageResource(R.drawable.c_file); 
    img1.setLayoutParams(mlp); 
    img1.setLongClickable(true); 
    img1.setId(img_id); 
    c_box.addView(img1); 

    img1.setOnTouchListener(listener); 

回答

4

終於讓我找到了一點:

FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
     LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 
     Gravity.NO_GRAVITY); 

,我錯過了第三個參數(Gravity.NO_GRAVITY)。使用它你可以在任何設置寬度/高度的位置放置視圖。

2

你可以使用MarginLayoutParams

MarginLayoutParams mlp = (MarginLayoutParams) yourImageViewHere.getLayoutParams(); 
mlp.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);//all in pixels 
yourImageViewHere.setLayoutParams(mlp); 

動態設置頁邊距。

+0

非常感謝。 imageview被創建並添加到父級後可以嗎? – kinglomei

+0

嗯,我認爲如果你在onDraw被調用後設置這些邊距,你將不得不重繪你的佈局。要強制重繪視圖,你可以說yourImageViewHere.invalidate();請參閱http://developer.android.com/reference/android/view/View.html#invalidate()。請接受我的答案,如果這對你有用。 –

+0

非常感謝。我很高興接受你的答案,如果這個問題解決了。我編輯了我的問題,添加了一些代碼。有什麼建議? – kinglomei

相關問題