2017-02-27 90 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)

相關問題