ビューの絶対位置を設定する 質問する

ビューの絶対位置を設定する 質問する

Android でビューの絶対位置を設定することは可能ですか? ( があることは知っていますAbsoluteLayoutが、非推奨になっています...)

たとえば、240x320 ピクセルの画面がある場合、ImageView中心が位置 (100,100) になるように 20x20 ピクセルのを追加するにはどうすればよいですか?

ベストアンサー1

RelativeLayout を使用できます。レイアウト内の位置 (50,60) に 30x40 の ImageView が必要だとします。アクティビティのどこかに次のコードがあります。

// Some existing RelativeLayout from your layout xml
RelativeLayout rl = (RelativeLayout) findViewById(R.id.my_relative_layout);

ImageView iv = new ImageView(this);

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 50;
params.topMargin = 60;
rl.addView(iv, params);

その他の例:

2 つの 30x40 ImageView (黄色 1 つと赤 1 つ) をそれぞれ (50,60) と (80,90) に配置します。

RelativeLayout rl = (RelativeLayout) findViewById(R.id.my_relative_layout);
ImageView iv;
RelativeLayout.LayoutParams params;

iv = new ImageView(this);
iv.setBackgroundColor(Color.YELLOW);
params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 50;
params.topMargin = 60;
rl.addView(iv, params);

iv = new ImageView(this);
iv.setBackgroundColor(Color.RED);
params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 80;
params.topMargin = 90;
rl.addView(iv, params);

30x40の黄色のImageViewを(50,60)に配置し、もう1つの30x40の赤色のImageViewを<80,90>に配置します。に関連して黄色のImageView:

RelativeLayout rl = (RelativeLayout) findViewById(R.id.my_relative_layout);
ImageView iv;
RelativeLayout.LayoutParams params;

int yellow_iv_id = 123; // Some arbitrary ID value.

iv = new ImageView(this);
iv.setId(yellow_iv_id);
iv.setBackgroundColor(Color.YELLOW);
params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 50;
params.topMargin = 60;
rl.addView(iv, params);

iv = new ImageView(this);
iv.setBackgroundColor(Color.RED);
params = new RelativeLayout.LayoutParams(30, 40);
params.leftMargin = 80;
params.topMargin = 90;

// This line defines how params.leftMargin and params.topMargin are interpreted.
// In this case, "<80,90>" means <80,90> to the right of the yellow ImageView.
params.addRule(RelativeLayout.RIGHT_OF, yellow_iv_id);

rl.addView(iv, params);

おすすめ記事