设置视图的绝对位置 [英] Set the absolute position of a view
问题描述
是否可以在 Android 中设置视图的绝对位置?(我知道有一个 AbsoluteLayout
,但它已被弃用...)
Is it possible to set the absolute position of a view in Android? (I know that there is an AbsoluteLayout
, but it's deprecated...)
例如,如果我有一个 240x320px 的屏幕,我如何添加一个 ImageView
,它是 20x20px,使其中心位于 (100,100) 位置?
For example, if I have a 240x320px screen, how could I add an ImageView
which is 20x20px such that its center is at the position (100,100)?
推荐答案
您可以使用 RelativeLayout.假设您想要在布局内的位置 (50,60) 处有一个 30x40 的 ImageView.您活动中的某处:
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:
分别在 (50,60) 和 (80,90) 处放置两个 30x40 ImageViews(一个黄色,一个红色):
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);
这篇关于设置视图的绝对位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!