Тег включения
<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 layout 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>
Вы сохранили один уровень иерархии, избегая одного бесполезного представления: Romain Guy уже спит лучше.
Разве ты не счастливее сейчас?
<TextView />ничем другим.