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 回答