我想在應用程序啓動的某個區域放置一些圖像。 由於圖像的數量不是固定的數量,所以我必須動態地創建圖像。 我想設置每張圖片的位置/邊距,以創造良好的平衡。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);
非常感謝。 imageview被創建並添加到父級後可以嗎? – kinglomei
嗯,我認爲如果你在onDraw被調用後設置這些邊距,你將不得不重繪你的佈局。要強制重繪視圖,你可以說yourImageViewHere.invalidate();請參閱http://developer.android.com/reference/android/view/View.html#invalidate()。請接受我的答案,如果這對你有用。 –
非常感謝。我很高興接受你的答案,如果這個問題解決了。我編輯了我的問題,添加了一些代碼。有什麼建議? – kinglomei