将 xml 导入到 java

Import xml to java

按下按钮时我想创建一些元素,例如 TextView 和 CheckBox。我现在可以在我的 java 代码中执行此操作,但是...是否可以拥有一个仅包含这些元素的 xml 文件并在按下按钮时调用它?

像这样:

java:

myButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //create whats in myxml

        }

这就是我想要创建的 (myxml.xml):

 <LinearLayout
    android:layout_width="fill_parent"
    android:orientation="horizontal"
    android:layout_height="wrap_content"
    android:background="@drawable/checkboxlayout"
    android:layout_marginTop="25px">

    <CheckBox
        android:layout_width="0dp"
        android:layout_weight=".7"
        android:layout_height="wrap_content"/>

    <LinearLayout
        android:layout_width="0dp"
        android:layout_weight=".3"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        android:background="@drawable/datelayout"
        android:gravity="center"
        >
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            >
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            >

    </LinearLayout>

</LinearLayout>

希望有人能帮忙

一种方法是使用 <include 标签将 组件布局 包含到 Activity/Fragment 的布局中。可以使用 findViewById 检索组件布局的内容。或者,您可以 LayoutInflater 转换 您的 xml,在 View.

例如

View view = getLayoutInflater().inflate(R.layout.name_of_layout, null);

其中 name_of_layout.xml 包含您要转换的组件。请注意,inflater returns 是一个全新的 View,如果您想处理,必须将其添加到 Activity/Fragment 的视图层次结构中有了它