2011-01-31 113 views
16

我一直在到處搜索這個問題的答案。我是Android新手,嘗試通過java代替xml以編程方式將項添加到相對佈局。我已經創建了一個測試類來嘗試它,但項目保持堆疊而不是格式正確。我只是希望對方下一個TextView的,現在(最終我將使用的參數的左側和右側,但我開始很簡單。我缺少什麼?以編程方式將項目添加到相對佈局

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    ScrollView sv = new ScrollView(this); 
    RelativeLayout ll = new RelativeLayout(this); 
    ll.setId(99); 
    sv.addView(ll); 
    TextView tv = new TextView(this); 
    tv.setText("txt1"); 
    tv.setId(1); 
    TextView tv2 = new TextView(this); 
    tv2.setText("txt2"); 
    tv2.setId(2); 
    RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
    lay.addRule(RelativeLayout.ALIGN_PARENT_TOP); 
    ll.addView(tv, lay); 
    RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
    p.addRule(RelativeLayout.ALIGN_BOTTOM, tv.getId()); 
    ll.addView(tv2, p); this.setContentView(sv);}; 

回答

20
p.addRule(RelativeLayout.ALIGN_BOTTOM, tv.getId()); 

此行意味着,底部我們強烈建議使用xml來代替它

+1

謝謝你,它實際上是RelativeLayout.Below,但足夠接近。做xml的問題最終會從外部數據庫填充。 – user597436 2011-01-31 20:45:45

2

你錯過了各種各樣的東西,比如說,它們會覆蓋對方,首先ScrollView沒有任何措施,第二個設置爲LayoutParams.FILL_PARENT或WRAP_CONTENT;它的TextView1放錯了位置,所以TextView2,s TextView1的位置與lay.addRule(RelativeLayout.ALIGN_PARENT_TOP,RelativeLayout.TRUE);

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    ScrollView sv = new ScrollView(this); 
    RelativeLayout ll = new RelativeLayout(this); 
    ll.setId(99); 

    sv.addView(ll, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); 

    TextView tv = new TextView(this); 
    tv.setText("txt1"); 
    tv.setId(1); 

    TextView tv2 = new TextView(this); 
    tv2.setText("txt2"); 
    tv2.setId(2); 
    RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
    lay.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE); 
    ll.addView(tv, lay); 
    RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
    p.addRule(RelativeLayout.ALIGN_BOTTOM, tv.getId()); 
    ll.addView(tv2, p); 
this.setContentView(sv);}; 
+0

這裏有一個錯誤,行p.addRule(RelativeLayout.ALIGN_BOTTOM,tv.getId());必須像@Cristian所說:p.addRule(RelativeLayout.BELOW,tv.getId()); – Franco 2011-01-31 20:45:20

5

用途:

p.addRule(RelativeLayout.BELOW, tv.getId()); 
相關問題