2014-10-07 45 views
0

我以編程方式設置我的佈局,因爲我填充它取決於我從請求中獲得多少圖像。我想要做的是在圖片右側創建兩個textview,第一個在第一個下面。隨着我在其他答案中發現的,我結束了我的第二個textview是重疊的圖像,並不低於其他textview。使textview在另一個textview下,並以編程方式在圖像的右側

int counter = 0; 
    while(mList.size()!=counter) 
    { 
     RelativeLayout row = new RelativeLayout(context); 
     row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));    

     ImageButton imgBtn = new ImageButton(context); 
     Bitmap image = getImage(mList.get(counter)); 
     imgBtn.setImageBitmap(image); 
     imgBtn.setId(counter + 1); // Because it need to be a positive integer. 
     imgBtn.setBackground(null); 
     imgBtn.setPadding(0, 0, 0, 0); 
     row.addView(imgBtn); 

     TextView firstText = new TextView(context); 
     RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); 
     lp.addRule(RelativeLayout.RIGHT_OF, imgBtn.getId()); 
     lp.addRule(RelativeLayout.CENTER_IN_PARENT); 
     firstText.setLayoutParams(lp); 
     firstText.setId(counter+100); 
     row.addView(firstText); 

     TextView secondText = new TextView(context); 
     RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); 
     lp2.addRule(RelativeLayout.BELOW,firstText.getId()); 
     secondText.setLayoutParams(lp2); 
     row.addView(secondText); 

     ++counter; 
     linlayout.addView(row); 
    } 

回答

1

使用linearLayout而不是relative.In在這裏你不需要設置counter和id。將setTag替換爲視圖。使代碼更具可讀性。

您可以設置行佈局的方向,然後不需要擔心其他參數來定位視圖。

我不添加代碼因爲我知道你可以寫得很好,只是改變方法。

+0

確實,我沒有任何重疊,但textView不是相對於像我想要的圖像,兩個textView只是一個接一個。有沒有辦法使用LinearLayout將第二個textview放置在第一個圖像的下方並且仍然在圖像的右側? – ggc 2014-10-07 19:06:46

+0

使用您的父母作爲LinearLayout L1,水平方向,然後將圖像添加到它(L1)。再次使用垂直方向的LinearLayout(L2),將兩個textView添加到它(L2),然後將L2添加到L1,您將得到結果 – 2014-10-07 19:14:00

+0

嗯,聽起來是對的。嘗試它 – ggc 2014-10-07 19:25:32

相關問題