如何在android中包含布局内部布局

moh*_*han 81 android android-layout

如何在Android中包含布局内部布局?

我正在创建共同的布局.我想将该布局包含在另一个页面中.

Mic*_*ose 169

编辑:正如在这里正确要求的评论更多信息.使用include标签

<include
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   layout="@layout/yourlayout" />
Run Code Online (Sandbox Code Playgroud)

包括要重用的布局.

检查此链接 ...

  • 只是一个小细节:使用android:layout_width ="match_parent"而不是android:layout_width ="fill_parent".不推荐使用fill_parent. (8认同)
  • 我可以包含一个布局并通过 xml 设置它的一些属性,例如直接在 &lt;include&gt; 标记中设置子布局中的文本字符串吗? (2认同)

Phi*_*o99 48

请注意,如果您包含android:id...<include />标记中,它将覆盖在包含的布局中定义的任何ID.例如:

<include
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:id="@+id/some_id_if_needed"
   layout="@layout/yourlayout" />
Run Code Online (Sandbox Code Playgroud)

yourlayout.xml:

<LinearLayout
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:id="@+id/some_other_id">
   <Button
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"
       android:id="@+id/button1" />
 </LinearLayout>
Run Code Online (Sandbox Code Playgroud)

然后,您将在代码中引用此包含的布局,如下所示:

View includedLayout = findViewById(R.id.some_id_if_needed);
Button insideTheIncludedLayout = (Button)includedLayout.findViewById(R.id.button1);
Run Code Online (Sandbox Code Playgroud)


GrA*_*And 19

使用<include />标签.

          <include 
            android:id="@+id/some_id_if_needed"
            layout="@layout/some_layout"/>
Run Code Online (Sandbox Code Playgroud)

另请参阅创建可重用UI组件合并布局文章.


Abh*_*bhi 6

试试这个

<include
            android:id="@+id/OnlineOffline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            layout="@layout/YourLayoutName" />
Run Code Online (Sandbox Code Playgroud)