设置的视图的绝对位置视图、位置

2023-09-11 11:31:49 作者:爱请你靠边

是否有可能设置在Android的视图的绝对位置? (我知道有一个AbsoluteLayout,但它去precated ...) 可以说,我有一个屏幕240x320px,我想提出一个ImageView的是20x20px,其在位置(100,100)中心。 我需要做什么? 感谢您的帮助,这是推动我疯了。

Is it possible to set the absolute position of a view in android? (I know that there is an AbsoluteLayout, but it's deprecated...) Lets say I have a screen 240x320px, and I want to put an ImageView which is 20x20px with its center at the position (100,100). What do I have to do? Thanks for the help, this is driving me crazy.

推荐答案

您可以使用RelativeLayout的。比方说,你想要一个30X40的ImageView在位置(50,60)的布局中。在某处你的活动:

You can use RelativeLayout. Let's say you wanted a 30x40 ImageView at position (50,60) inside your layout. Somewhere in your activity:

// 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);

更多的例子:

More examples:

两处30X40 ImageViews(一黄,一红)在(50,60)和(80,90),分别为:

Places two 30x40 ImageViews (one yellow, one red) at (50,60) and (80,90), respectively:

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),另一个30X40红色的ImageView< 80,90> 相对黄色ImageView的:

Places one 30x40 yellow ImageView at (50,60) and another 30x40 red ImageView <80,90> relative to the yellow 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);