35

XML で UI レイアウトを作成し、それを子として既存のビューに挿入したいと考えています (複数回挿入されます)。

たとえば、XML ファイルの内容は次のとおりです。

<RelativeLayout
    android:id="@+id/relativeLayout1" >
    <Button android:id="@+id/myButton"
        android:text="@string/mystring" />
</RelativeLayout>

今、私は親を取得し、LinearLayoutその XML ファイルを子ビューとして追加したいと考えています。

LinearLayout linear = (LinearLayout) findViewById(R.id.myLayout);

// need to create a view object from the xml file
linear.addView(myXmlObject);

XML リソースをビュー タイプに変換することはできますか? もしそうなら、どうすればいいですか?

4

1 に答える 1

97

LayoutInflaterが必要だと思います。サンプルの XML がファイルにあるとしましょうcustom_layout.xml:

LayoutInflater inflater = LayoutInflater.from(context);
RelativeLayout layout = (RelativeLayout) inflater.inflate(R.layout.custom_layout, null, false);

LinearLayout linear = (LinearLayout)findViewById(R.id.myLayout);
linear.addView(layout);
于 2012-12-15T04:19:23.863 に答える