ALIGN_PARENT_TOP以编程方式不起作用
为什么这不起作用?ALIGN_PARENT_TOP以编程方式不起作用
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);
}
成功正在添加的的ImageView的XML
<RelativeLayout
android:id="@+id/PLAY_Mat"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
>
</RelativeLayout>
,但它为中心垂直。我希望它对齐到顶部。 我希望这是即使没有添加规则的方式,因为“默认情况下,所有子视图都在布局的左上角绘制”(RelativeLayout文档)。
设置MATCH_PARENT到RelativeLayout
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(new ViewGroup.LayoutParams(CardWidth, ViewGroup.LayoutParams.MATCH_PARENT));
或
你可以使用getLayoutParams()的RelativeLayout
从XML
RelativeLayout.LayoutParams lp = parentRelativeImageview.getLayoutParams();
试试这个代码:
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)图像的宽度是我设置的150,因为原生尺寸比这更大(我需要缩小它)。 2)你将图像添加到rl。我将它添加到mat(我对所需的父视图组的引用)。 – ausgeorge
这实际上起作用,但前提是我使用图像的原始大小(WRAP_CONTENT)。如果我使用像素值,则图像再次居中。不幸的是,我的图像的大小/规模因条件而异。 – ausgeorge
你可以使用dp代替你的图片而不是像素。 – rafsanahmad007
解决方案由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)
。
我将您的解决方案移至社区wiki答案。 –