【问题标题】:How to embed one layout inside another in my case?在我的情况下,如何将一种布局嵌入到另一种布局中?
【发布时间】:2011-10-01 01:45:48
【问题描述】:

如果我有一个名为 bottom.xml 的布局,

bottom.xml:(只包含一个文本视图和编辑文本视图)

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:orientation="vertical"
     >
        <TextView 
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:gravity="center_horizontal" 
            android:text="@string/username"

        />

        <EditText 
            android:id="@+id/name"

            android:layout_width="120dip"
            android:layout_height="50dip"
            android:layout_gravity="center_horizontal"     
        />
 </LinearLayout>

有没有办法将上述 bottom.xml 布局嵌入到其他布局中,而不是在多个布局文件中重复编写相同的代码(当其他布局有一部分包含与bottom.xml相同的布局时)?

例如,如果我的 admin.xml 布局还包含与 bottom.xml完全相同的部分布局>,如何将 bottom.xml 嵌入到 admin.xml 中,而不是编写还是一样的代码?

admin.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
     >
     ...
     ...
        <!--How to embed bottom.xml here-->
     ...
 </LinearLayout>

如果在 Android 中无法做到这一点,有什么解决方法??

---------更新-----------

就像@xevincent 建议的那样,我可以通过使用&lt;include&gt; 标签来重用bottom.xml

但是如何更改重新布局中元素的 id 呢?

比如insdie bottom.xml,我想在复用的时候把&lt;editText android:id="@+id/name"&gt;的id改成&lt;editText android:id="@+id/other_name"&gt; bottom.xml 其他布局中的布局,如何修改id?

【问题讨论】:

标签: android android-layout android-emulator android-widget android-manifest


【解决方案1】:

请参阅此文档reusing layouts

【讨论】:

  • @xevincent ,如何更改重新布局中元素的 id,例如bottom.xml,我想在其他布局中重用bottom.xml布局时更改editText的id,如何更改id?
  • 您不能以xml方式更改bottom.xml中元素的id,但您可以在Java中进行(参见View.setId(int))。
【解决方案2】:

只需对 xevincent 的回答投赞成票即可。我添加了这个答案,因为 SO 建议“始终引用重要链接的最相关部分,以防目标站点无法访问或永久脱机。”

所以,基本上,his link 解释说你应该使用&lt;include /&gt;

<com.android.launcher.Workspace
    android:id="@+id/workspace"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"

    launcher:defaultScreen="1">

    <include android:id="@+id/cell1" layout="@layout/workspace_screen" />
    <include android:id="@+id/cell2" layout="@layout/workspace_screen" />
    <include android:id="@+id/cell3" layout="@layout/workspace_screen" />

</com.android.launcher.Workspace>

并且知道你可以覆盖布局参数:

<include android:layout_width="fill_parent" layout="@layout/image_holder" />

【讨论】:

    【解决方案3】:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多