使用以下内容:
View v =getLayoutInflater().inflate(R.layout.mylayout,null)
// inflate mylayout.xml with other views
CustomRelativeLayout cs = new CustomRelativeLayout(this)
// CustomRelativeLayout is a class that extends RelativeLayout
cs.addView(v)
setContentView(cs)
例子:
示例:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="111dp"
android:text="TextView" />
</RelativeLayout>
SView
public class SView extends RelativeLayout {
Paint p,paint;
public SView(Context context) {
super(context);
TextView tv = new TextView(context);
tv.setText("hello");
this.addView(tv);
}
}
在MainActivity中。
View v =getLayoutInflater().inflate(R.layout.mylayout,null);
SView cs = new SView(this);
cs.addView(v);
setContentView(cs);
Snap
编辑:
如果您希望在CustomRelative布局中进行填充
在构造函数中
LayoutInflater inflater = LayoutInflater.from(context)
View v =inflater.inflate(R.layout.mylayout,null)
TextView tv = new TextView(context)
tv.setText("hello")
this.addView(tv)
this.addView(v)
CustomRelativeLayout cs = new CustomRelativeLayout(this);
现在你可以像这样创建文本视图TextView tv = new TextView(this); tv.setText("hello");
然后将文本视图添加到相对布局中cs.addView(tv);
,不需要使用 mylayout。 - Raghunandan