当我使用这个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
有任何想法吗?
谢谢!
最佳答案
您永远不会设置布局参数:
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);
?