It is used to reuse layout and reduce code redundancy. It is simple to use, as follows:
Included layout Title bar.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/inner_id"
android:layout_width="match_parent"
android:background="#ff009999"
android:layout_height="48dp">
<TextView
android:textSize="13sp"
android:text="Return"
android:textColor="@android:color/white"
android:layout_marginLeft="18dp"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:textSize="18sp"
android:text="Title Block"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textColor="@android:color/white"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Main layout activity main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.liang.optimizedemo.MainActivity">
<include
android:id="@+id/outter_id"
layout="@layout/title_bar"
/>
</RelativeLayout>
It is very simple to use. Here are just two notes:
1. When the ID (inner ID) is specified in the include d layout and the ID (outer ID) is specified in the main layout, the inner ID will be invalid and findviewbyid (r.id.inner ID) will return null
2. The other layout * properties take effect when and only if the layout? Width and layout? Height properties are set in the include tab of the main layout.
For example, the title bar.xml does not change, and the activity main.xml is changed as follows:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.liang.optimizedemo.MainActivity">
<TextView
android:id="@+id/hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Hello World!" />
<include
android:id="@+id/outter_id"
layout="@layout/title_bar"
android:layout_below="@id/hello" />
</RelativeLayout>
Then an error message will appear
After you specify the layout width and layout height properties, you can do the following:
<include
android:id="@+id/outter_id"
layout="@layout/title_bar"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_below="@id/hello" />
It should also be noted that when the layout width and layout height attributes are set in the include tag, the layout width and layout height attributes of the outermost layout of Title bar.xml will fail, which should be well understood?