2

当我使用这个 XML 文件时......

<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); 
}

...我看到背景颜色匹配父项而不是包装内容

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

有任何想法吗?

谢谢!

4

1 回答 1

2

你永远不会设置布局参数:

layout.setLayoutParams(params);

我认为你应该放置:

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

以及在设置布局参数之前您将添加到布局中的所有其他视图,否则将没有内容可以环绕。

编辑:

设置时会发生什么:

tried to replace between the two:

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

?

于 2013-03-23T22:40:19.273 回答