2013-03-23 42 views
2

,當我用這個XML文件...setBackgroundColor(INT顏色)和RelativeLayout的

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:id="@+id/RelativeLayout1" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:background="#FF0000" 

tools:context=".MainActivity" > 

<TextView 
    android:id="@+id/textView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"   
    android:text="@string/hello_world" /> 

</RelativeLayout> 

..我看到,背景色包裝內容

http://img716.imageshack.us/img716/8225/rlayout.jpg

但如果我寫這篇文章的RelativeLayout通過代碼...

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    RelativeLayout layout = new RelativeLayout(this); 

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
      RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 


    layout.setBackgroundColor(Color.parseColor("#FF0000")); 

    TextView text = new TextView(this); 
    text.setText("Hello world"); 

    //Añado texto 
    layout.addView(text); 

    layout.setLayoutParams(params); 

    setContentView(layout); 
} 

...我看到背景色m ATCH父母,而不是包裝內容

http://img404.imageshack.us/img404/1427/rlayoutfull.jpg

任何想法?

謝謝!

回答

2

你永遠不會設置佈局PARAMS:

layout.setLayoutParams(params); 

,我認爲你應該把:

TextView text = new TextView(this); 
text.setText("Hello world"); 

和所有其他視圖中,您將您之前添加到您的佈局設置佈局params,否則將沒有內容可以繞回。

編輯:

當你設置發生了什麼:

tried to replace between the two: 

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
     RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 

+0

我得到相同的結果...我不明白爲什麼....因爲我認爲我的代碼和XML文件是相同的= S – Bae 2013-03-23 22:44:09

+0

查看更新的答案。 – 2013-03-23 22:45:43

+0

我忘了「layout.setLayoutParams」!現在我試圖將textview添加到RelativeLayout,然後將params添加到relativelayout但我得到相同的結果:S – Bae 2013-03-23 22:53:32