【问题标题】:Include an existing XML layout file in another XML layout file在另一个 XML 布局文件中包含现有 XML 布局文件
【发布时间】:2013-07-30 18:56:10
【问题描述】:

我在名为 intro_step1_activity.xml 的文件中定义了一个 LinearLayout。我想在另一个 xml 文件中加载/引用这个文件,这样我就不需要在另一个 xml 文件中重新键入代码。这可能吗?如果可以,怎么做?

【问题讨论】:

    标签: android android-layout layout-inflater


    【解决方案1】:

    在运行时您可以使用充气机,例如:

    Inflater inflater = LayoutInflater.from(this);
    View view = inflater.inflate(R.layout.intro_step1_activity, null);
    

    然后您可以将此视图添加到当前视图层次结构中。在编译时,您可以使用 xml 的 include 标记

    <include layout="@layout/intro_step1_activity"/>
    

    【讨论】:

    • 来自 Android 文档:从不直接使用。相反,使用 getLayoutInflater() 或 getSystemService(String) 来检索标准 LayoutInflater 实例,该实例已连接到当前上下文并为您正在运行的设备正确配置。例如:LayoutInflater inflater = (LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);
    【解决方案2】:
    Load an existing xml layout file in another xml layout file
    

    要在其他 xml 文件中使用 xml 文件,请使用 &lt;include /&gt;

    为您的intro_step1_activity.xml 使用代码

    <include layout="intro_step1_activity.xml"/>
    

    【讨论】:

    • &lt;include layout="@layout/my_layout_file"/&gt; 似乎也有效
    【解决方案3】:

    是的,可以使用&lt;merge&gt;&lt;include&gt;

    你可以阅读更多herehere

    【讨论】:

      【解决方案4】:

      首先给那个LinearLayout一个id,然后在java中定义一个LinearLayout并使用findViewById()方法引用它。

      然后使用刚刚创建的LinearLayout 对象调用addView() 方法。

      如果你想要一个例子,请评论。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-05-24
        • 1970-01-01
        • 1970-01-01
        • 2021-09-23
        • 1970-01-01
        • 2021-10-03
        • 2022-08-04
        • 1970-01-01
        相关资源
        最近更新 更多