如何在RelativeLayout中显示一些ImageView?

时间:2011-06-08 08:48:49

标签: android imageview relativelayout

我有一个RelativeLayout

RelativeLayout myLayout = new RelativeLayout(this);

然后,我在此布局中添加了2个ImageView:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(20, 20);

ImageView img1 = new ImageView(this);
// Here I give the position of img1

ImageView img2 = new ImageView(this);
// And here the position and img2

myLayout.addView(img1, params);
myLayout.addView(img2, params);
setContentView(myLayout);

这里我遇到了一个问题:我想显示并点击2个ImageViews,但只有img2在我的屏幕上可见。

是否存在z-index或其他问题?

1 个答案:

答案 0 :(得分:3)

由于您使用RelativeLayout并且同一params用于两个ImageView,因此一个将与另一个重叠。因此,为两者定义参数。 Add rule每个参数用于定位它。然后给addView()

例如:

RelativeLayout myLayout = new RelativeLayout(this);

ImageView img1 = new ImageView(this);
RelativeLayout.LayoutParams firstImageParams = new RelativeLayout.LayoutParams(
android.view.ViewGroup.LayoutParams.WRAP_CONTENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
leftArrowParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);

ImageView img2 = new ImageView(this);
RelativeLayout.LayoutParams secImageParams = new RelativeLayout.LayoutParams(
android.view.ViewGroup.LayoutParams.WRAP_CONTENT,android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
rightArrowParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

myLayout.addView(img1, firstImageParams);
myLayout.addView(img2, secImageParams);
setContentView(myLayout);