是否可以在 Android 中设置视图的绝对位置?(我知道有一个AbsoluteLayout,但它已被弃用......)
AbsoluteLayout
例如,如果我有一个 240x320px 的屏幕,我如何添加一个 20x20px 的屏幕,ImageView使其中心位于 (100,100) 位置?
ImageView
您可以使用相对布局。假设您想要在布局内的位置 (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);
更多示例:
分别在 (50,60) 和 (80,90) 放置两个 30x40 ImageView(一个黄色,一个红色):
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:
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);