为什么这不起作用?
for (PlayingCard playingCard : Stack0.Cards)
{
ImageView myImg = new ImageView(this);
myImg.setImageResource(R.drawable.c2);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(new ViewGroup.LayoutParams(CardWidth, ViewGroup.LayoutParams.WRAP_CONTENT));
lp.setMargins(0, 0, 0,0);
//lp.addRule(RelativeLayout.ALIGN_TOP); fails
//lp.addRule(RelativeLayout.ALIGN_PARENT_TOP); fails
//lp.addRule(RelativeLayout.ALIGN_START); fails
lp.addRule(RelativeLayout.ALIGN_PARENT_START);
myImg.setLayoutParams(lp);
mat.addView(myImg);
}
xml
<RelativeLayout
android:id="@+id/PLAY_Mat"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
>
</RelativeLayout>
ImageView已成功添加,但它居中垂直。我希望它与顶部对齐。 我希望即使没有添加规则也可以这样做,因为“默认情况下,所有子视图都是在布局的左上角绘制的”(RelativeLayout文档)。
答案 0 :(得分:1)
试试这段代码:
RelativeLayout rl = new RelativeLayout(this);
for (PlayingCard playingCard : Stack0.Cards)
{
ImageView myImg = new ImageView(this);
myImg.setImageResource(R.drawable.c2);
RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
lay.setMargins(0, 0, 0,0);
lay.addRule(RelativeLayout.ALIGN_PARENT_TOP);
rl.addView(myImg, lay);
//myImg.setLayoutParams(lp);
//mat.addView(myImg);
}
答案 1 :(得分:0)
将 MATCH_PARENT 设置为RelativeLayout
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(new ViewGroup.LayoutParams(CardWidth, ViewGroup.LayoutParams.MATCH_PARENT));
或
您可以使用RelativeLayout
XML
的 getLayoutParams()
RelativeLayout.LayoutParams lp = parentRelativeImageview.getLayoutParams();
答案 2 :(得分:0)
OP解决方案。
此代码有效:
for (PlayingCard playingCard : Stack0.Cards)
{
ImageView myImg = new ImageView(this);
myImg.setImageResource(R.drawable.a1);
RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(CardWidth, CardHeight);
lay.setMargins(playingCard.UI_MarginLeft, playingCard.UI_MarginTop, 0, 0);
mat.addView(myImg, lay);
}
这里的关键是CardWidth和CardHeight都已设置,两者都正确。通过正确,我的意思是正确的比率。想要加宽宽度?然后加倍高度等。如果w或h中的一个是像素int,而另一个是WRAP_CONTENT,那么就会出现奇怪现象(图像形式有上边距或左边距)。
正确设置w和h后,不需要lp.addRule(RelativeLayout.ALIGN_PARENT_START)
。