我想添加View
,但它无法显示View
并且在运行时未发现错误
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.relative_null);
RelativeLayout relativeLayout= (RelativeLayout)
getLayoutInflater().inflate(R.layout.relative_null,null);
TextView tv = new TextView(this);
tv.setText("Hello World");
RelativeLayout.LayoutParams layoutParams=new RelativeLayout.LayoutParams
(80,80);
layoutParams.addRule(RelativeLayout.RIGHT_OF,R.id.button1);
layoutParams.addRule(RelativeLayout.BELOW,R.id.button1);
tv.setLayoutParams(layoutParams);
relativeLayout.addView(tv);
}
这是我的xml R.layout.relative_null
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/myRelativeLayout">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button1"/>
</RelativeLayout>
答案 0 :(得分:1)
您并没有正确添加textview。您正在将textview添加到您自己夸大的布局中。该布局与您通过setContentView()
看到的布局不同。你不需要给另一个人充气。这是更新后的代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.relative_null);
RelativeLayout relativeLayout= (RelativeLayout) findViewById(R.id.myRelativeLayout);
// tv init below
TextView tv = new TextView(this);
tv.setText("Hello World");
RelativeLayout.LayoutParams layoutParams=new RelativeLayout.LayoutParams
(80,80);
layoutParams.addRule(RelativeLayout.RIGHT_OF,R.id.button1);
layoutParams.addRule(RelativeLayout.BELOW,R.id.button1);
tv.setLayoutParams(layoutParams);
relativeLayout.addView(tv);
}