Layout Resource官方教程(3)在layout中用include嵌入其它layout

时间:2024-10-02 17:37:38

简介

<include>Includes a layout file into this layout.

类似 #include ,把layout展开在include处

attributes:

layout Layout resourceRequired. Reference to a layout resource.
android:id Resource ID. Overrides the ID given to the root view in the included layout.
android:layout_height Dimension or keyword. Overrides the height given to the root view in the included layout. Only effective if android:layout_width is also declared.
android:layout_width Dimension or keyword. Overrides the width given to the root view in the included layout. Only effective if android:layout_height is also declared.

  You can include any other layout attributes in the <include> that are supported by the root element in the included layout and they will override those defined in the root element.

注意,findViewById()都是父容器找子控件,被include的 layout里的控件要在都位于主layout中,所以要用 主layout对应的view.findViewById()才能找到子layout中的控件。

Caution:

  If you want to override layout attributes using the <include> tag, you must override both android:layout_height and android:layout_width in order for other layout attributes to take effect.

  Another way to include a layout is to use ViewStub. It is a lightweight View that consumes no layout space until you explicitly inflate it, at which point, it includes a layout file defined by itsandroid:layout attribute. For more information about using ViewStub, read Loading Views On Demand.

示例:

主layout: frgmt_main.xml

   <FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent"> <!-- tab1,用include可以引用别处的layout -->
<include
android:id="@+id/tab_weixin" android:layout_width="wrap_content"
android:layout_height="wrap_content"
layout="@layout/tab_weixin_layout" />

被include的layout :  tab_weixin_layout.xml

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/tab_weixin_layout"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/tab_weixin_qq_friend"
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="wrap_content" > <ImageView
android:id="@+id/iv_tab_weixin_qq_friend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="centerInside"
android:src="@drawable/tab_weixin_qq_scale" /> <TextView
android:id="@+id/tv_tab_weixin_qq_friend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/find_qq_friends" /> </LinearLayout> <ListView
android:id="@+id/tab_weixin_list"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView> </LinearLayout>