Тег включения
Тег <include>
позволяет разделить макет на несколько файлов: он помогает работать с сложным или слишком длинным пользовательским интерфейсом.
Предположим, вы разбили сложный макет, используя два включаемых файла, следующим образом:
top_level_activity.xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- First include file -->
<include layout="@layout/include1.xml" />
<!-- Second include file -->
<include layout="@layout/include2.xml" />
</LinearLayout>
Тогда вам нужно написать include1.xml
и include2.xml
.
Имейте в виду, что xml из включаемых файлов просто выгружается в вашем top_level_activity
макете во время рендеринга (почти как макрос #INCLUDE
для C).
Включаемые файлы представляют собой простой формат jane xml.
include1.xml :
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textView1"
android:text="First include"
android:textAppearance="?android:attr/textAppearanceMedium"/>
... и include2.xml :
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/button1"
android:text="Button" />
Видите?Ничего фантастического.Обратите внимание, что вам все равно нужно объявить пространство имен Android с помощью xmlns:android="http://schemas.android.com/apk/res/android
.
. Таким образом, отрисованная версия top_level_activity.xml имеет вид:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- First include file -->
<TextView
android:id="@+id/textView1"
android:text="First include"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<!-- Second include file -->
<Button
android:id="@+id/button1"
android:text="Button" />
</LinearLayout>
В вашем Java-коде все это прозрачно: findViewById(R.id.textView1)
в вашем классе активности возвращает правильный виджет (даже если этот виджет был объявлен в XML-файле, отличном от макета активности).
И вишнясверху: визуальный редактор плавно справляется с этой задачейМакет верхнего уровня отображается с включенным xml.
График утолщается
Поскольку включаемый файл является классическим XML-файлом макета, это означает, что он должен иметь одинверхний элемент.Таким образом, в случае, если ваш файл должен содержать более одного виджета, вы должны будете использовать макет.
Предположим, что include1.xml
теперь имеет два TextView
: макет должен быть объявлен.Давайте выберем LinearLayout
.
include1.xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:text="Second include"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<TextView
android:id="@+id/textView2"
android:text="More text"
android:textAppearance="?android:attr/textAppearanceMedium"/>
</LinearLayout>
top_level_activity.xml будет отображаться как:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- First include file -->
<LinearLayout
android:id="@+id/layout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:text="Second include"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<TextView
android:id="@+id/textView2"
android:text="More text"
android:textAppearance="?android:attr/textAppearanceMedium"/>
</LinearLayout>
<!-- Second include file -->
<Button
android:id="@+id/button1"
android:text="Button" />
</LinearLayout>
Но подождите, что два уровня LinearLayout
являются избыточными !
Действительно, два вложенных LinearLayout
не служат цели, так как два TextView
могут быть включеныпод layout1
для точно такой же рендеринг .
Так что же мы можем сделать?
Введите тег объединения
Тег <merge>
- это всего лишь фиктивный тег, который предоставляет элемент верхнего уровня для решения проблем избыточности такого типа.
Сейчас include1.xml становится:
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="@+id/textView1"
android:text="Second include"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<TextView
android:id="@+id/textView2"
android:text="More text"
android:textAppearance="?android:attr/textAppearanceMedium"/>
</merge>
и теперь top_level_activity.xml отображается как:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- First include file -->
<TextView
android:id="@+id/textView1"
android:text="Second include"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<TextView
android:id="@+id/textView2"
android:text="More text"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<!-- Second include file -->
<Button
android:id="@+id/button1"
android:text="Button" />
</LinearLayout>
Вы сохранили один уровень иерархии, избегайте одногобесполезный взгляд: Ромэн Гай уже спит лучше.
Разве ты не счастливее сейчас?