2011-07-05 69 views
10

我正在試圖使用動態佈局來評論我的項目部分,但是當我動態地設置textview的輸出時,輸出只出現在屏幕頂部。它把輸出通過其他輸出動態TextView在相對佈局

RelativeLayout ll=(RelativeLayout) findViewById(R.id.rl); 
     for(int i = 0; i < 20; i++) { 
     TextView cb = new TextView(this); 
     cb.setText("YORUMLAR"+yorum[0]+i); 

     cb.setTextSize(30); 
      ll.addView(cb); 

     } 

所以我怎麼能把輸出線性的底部的屏幕。

+1

...通過設置適當的相對屬性到您的textViews;現在,您只是設置文本,沒有位置,默認情況下它在屏幕上方。 – Adinia

回答

21

您應該使用LinearLayout自動添加一個接一個TextView


假設你的生活不能沒有RelativeLayout,則需要動態生成你要想把一個視圖下的另一個創造一切TextView IDS。下面是例子:

public class HelloWorld extends Activity 
{  
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    {  
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity); 

     RelativeLayout layout = (RelativeLayout)findViewById(R.id.layout); 

     Random rnd = new Random(); 
     int prevTextViewId = 0;  
     for(int i = 0; i < 10; i++) 
     {      
      final TextView textView = new TextView(this); 
      textView.setText("Text "+i);  
      textView.setTextColor(rnd.nextInt() | 0xff000000);    

      int curTextViewId = prevTextViewId + 1; 
      textView.setId(curTextViewId); 
      final RelativeLayout.LayoutParams params = 
       new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, 
               RelativeLayout.LayoutParams.WRAP_CONTENT); 

      params.addRule(RelativeLayout.BELOW, prevTextViewId); 
      textView.setLayoutParams(params); 

      prevTextViewId = curTextViewId; 
      layout.addView(textView, params); 
     }    
    }  
} 

enter image description here

+0

非常感謝!我有一個可以有空值的遊標。人們討厭看到空白的東西,所以我使用「if not null,do this」語句創建了一個動態文本視圖,然後使用您的示例爲每個需要查看的動態文本視圖ID生成動態文本視圖ID。 關鍵是在每個if語句中設置curTextViewId = prevTextViewID + 1,然後在每個語句的結尾處確保設置prevTextViewId = curTextViewId,以便下一個if語句獲取新的prevTextViewId。 謝謝! – Opy

2

您對您提供新添加視圖的位置。正如@Adinia所說,沒有立場,默認情況下它將與頂端對齊。所以你可以使用下面的代碼用RelativeLayout來完成它;

RelativeLayout containerLayout = (RelativeLayout) findViewById(R.id.container); 

for (int i = 0; i < 20; i++) { 

    TextView dynaText = new TextView(this); 

    dynaText.setText("Some text " + i); 
    dynaText.setTextSize(30); 

    // Set the location of your textView. 
    dynaText.setPadding(0, (i * 30), 0, 0); 

    containerLayout.addView(dynaText); 
} 

如果您想要一個接一個地顯示多個文字瀏覽,那麼您應該使用LinearLayout。

1

您也可以將Dynamic textview添加到相對佈局。在這裏,我附上了一些代碼,這可能會幫助你。

RelativeLayout ll=(RelativeLayout) findViewById(R.id.rl); 
    for(int i = 0; i < 20; i++) 
    { 
     TextView cb = new TextView(this); 
     cb.setText("YORUMLAR"+yorum[0]+i); 
     cb.setTextSize(30); 
     cb.setId(2000+i); 
     RelativeLayout.LayoutParams TextViewLayoutParams = new RelativeLayout.LayoutParams(100,100); 
     if (i != 0)DispViewLayoutParams.addRule(RelativeLayout.BELOW, 2000 - (i-1)); 
     ll.addView(cb,TextViewLayoutParams); 
    }