当我使用这个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
有什么想法吗?
谢谢!
答案 0 :(得分: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);