在Android上使用XML以编程方式创建视图

Ano*_*aly 29 xml android

我想用XML创建一个UI布局,并将其作为子项插入到现有视图中(它将被多次插入).

例如,以下是XML文件将包含的内容:

<RelativeLayout
    android:id="@+id/relativeLayout1" >
    <Button android:id="@+id/myButton"
        android:text="@string/mystring" />
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)

现在我得到父LinearLayout,现在想要将该XML文件添加为子视图,例如:

LinearLayout linear = (LinearLayout)findViewById(R.id.myLayout);
//need to create a view object from the xml file
linear.addView(myXmlObject);
Run Code Online (Sandbox Code Playgroud)

是否可以将XML资源转换为视图类型?如果是这样,我该怎么做?

Sam*_*Sam 80

我相信你想要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);
Run Code Online (Sandbox Code Playgroud)

  • 你是如何处理按钮点击的?我的意思是每一行的按钮点击都有不同的功能。 (3认同)