2017-02-27 107 views
0

为什么这不起作用?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文档)。

+0

我将您的解决方案移至社区wiki答案。 –

回答

0

设置MATCH_PARENTRelativeLayout

RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(new ViewGroup.LayoutParams(CardWidth, ViewGroup.LayoutParams.MATCH_PARENT)); 

你可以使用getLayoutParams()的RelativeLayoutXML

RelativeLayout.LayoutParams lp = parentRelativeImageview.getLayoutParams(); 
+0

这是行不通的,对不起 – ausgeorge

+0

你试过'RelativeLayout.ALIGN_PARENT_TOP'而不是'START' –

+0

试过了(添加规则ALIGN_PARENT_TOP),也不起作用。 – ausgeorge

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); 
    } 
+0

不起作用。图像垂直居中。我确实改变了两件事。 1)图像的宽度是我设置的150,因为原生尺寸比这更大(我需要缩小它)。 2)你将图像添加到rl。我将它添加到mat(我对所需的父视图组的引用)。 – ausgeorge

+0

这实际上起作用,但前提是我使用图像的原始大小(WRAP_CONTENT)。如果我使用像素值,则图像再次居中。不幸的是,我的图像的大小/规模因条件而异。 – ausgeorge

+0

你可以使用dp代替你的图片而不是像素。 – rafsanahmad007

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)

相关问题