使用下面
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); // add the view to relative layout
setContentView(cs); // set the custom relative layout to activity
實施例:
<?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);
}
}
在MainActivtiy
View v =getLayoutInflater().inflate(R.layout.mylayout,null);
SView cs = new SView(this);
cs.addView(v);
setContentView(cs);
捕捉

編輯:
如果你想在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);
這樣我會得到一個額外的嵌套層次,這將不需要 - 我將有一個relativeLayout(CS)和一些額外的根佈局(mylayout),這將嵌套。其中之一是無用的。 – stoefln
@stoefln所以我可能誤解了你的問題可以更清楚或發佈一些代碼片段指示你迄今爲止做了什麼。其中之一是沒用的沒有。實際上你可以動態地創建一個textview並添加到自定義的相對佈局,在這種情況下你不需要mylayout – Raghunandan
@stoefln'CustomRelativeLayout cs = new CustomRelativeLayout(this);'現在你可以像TextView tv = new TextView (這個); tv.setText(「hello」);'現在將textview添加到像'cs.addView(tv);'這樣的相對佈局中。'不需要mylayout – Raghunandan