No Image

Android studio include layout

СОДЕРЖАНИЕ
268 просмотров
10 марта 2020

Освой программирование играючи

/* Моя кошка замечательно разбирается в программировании. Стоит мне объяснить проблему ей — и все становится ясно. */
John Robbins, Debugging Applications, Microsoft Press, 2000

Читайте на здоровье!

Статья проплачена кошками — всемирно известными производителями котят.

Если статья вам понравилась, то можете поддержать проект.

В секции Custom можно увидеть компонент . Если вы имели дело с PHP, то данный тег вам уже знаком. Он позволяет вставить заранее подготовленный кусок разметки в вашу разметку. Зачем это нужно? Представьте себе, что у вас сложное приложение, состоящее из нескольких активностей. И в каждой активности есть один и тот же одинаковый элемент, например, футер для отображения логотипа компании или текста. Чтобы не повторять одинаковый блок в каждой активности по отдельности, можно создать отдельную разметку и через include добавлять в нужное место.

Подготовим заранее нужную разметку и сохраним его в отдельном файле папки res/layout:

res/layout/excerpt_content.xml

Теперь возвращаемся к основной активности, где уже есть кнопки, метки и текстовое поле, и добавляем подготовленную разметку через include:

Как видите, вам нужно указать в атрибуте layout нужную разметку и его содержимое отобразится на экране активности. Подобный подход может существенно сэкономить ресурсы для сложной разметки.

Кстати, вы можете переопределять различные параметры источника, указывая свои значения для разных макетов.

Если вы выберете в режиме дизайна, то появится диалоговое окно, в котором нужно выбрать созданный вами макет.

Тег помогает устранить избыточную группировку, когда один шаблон включается в другой. Например, если ваш основной шаблон – вертикальный LinearLayout, в котором два последовательных компонента могут быть повторно использованы в различных других разметках, то повторно используемый шаблон, в котором вы размещаете два компонента, требует свой корневой элемент. Однако, использование другого LinearLayout как корневого элемента для повторно используемого Layout приведет к вертикальному LinearLayout внутри вертикального LinearLayout. Вложенный LinearLayout уменьшает производительность работы пользовательского интерфейса и не нужен для работы.

Читайте также:  Как открыть сохраненную ссылку

Чтобы избежать избыточной группировки элементов View, вы можете использовать как корневой элемент для повторного использования шаблона. Например:

Теперь, когда вы подключает шаблон в другой с использованием тега , система игнорирует элемент и помещает две кнопки непосредственно в разметку на месте тега .

How to include layout inside layout in Android?

I am creating common layout. I want to include that layout in another page.

5 Answers 5

Edit: As in a comment rightly requested here some more information. Use the include tag

to include the layout you want to reuse.

Note that if you include android:id. into the tag, it will override whatever id was defined inside the included layout. For example:

Then you would reference this included layout in code as follows:

From Official documents about Re-using Layouts

Although Android offers a variety of widgets to provide small and re-usable interactive elements, you might also need to re-use larger components that require a special layout. To efficiently re-use complete layouts, you can use the tag to embed another layout inside the current layout.

Here is my header.xml file which i can reuse using include tag

No I use the tag in XML to add another layout from another XML file.

When designing the Android layout file, we sometimes might need to re-use larger components that require a special layout. To efficiently achieve this, we can use the tag to embed another layout inside the current layout.

Create a Re-usable Layout

Create a new XML file and define the layout. For example, here is a XML layout file mojo_introduction_layout.xml from the app MojoTeahouse.

Use the “include” Tag

Inside the layout to which we want to add the re-usable component, add the tag. For example, here’s a layout from the activity_about.xml that includes the mojo_introduction_layout from above.

Читайте также:  Частица движется в плоскости xy по закону

We can also override all the layout parameters (any android:layout_* attributes) of the included layout’s root view by specifying them in the tag. For example:

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

Use the “merge” Tag

This following section is cited from the Android document. We haven’t tried the tag in our application yet.

The tag helps eliminate redundant view groups in your view hierarchy when including one layout within another. For example, if your main layout is a vertical LinearLayout in which two consecutive views can be re-used in multiple layouts, then the re-usable layout in which you place the two views requires its own root view. However, using another LinearLayout as the root for the re-usable layout would result in a vertical LinearLayout inside a vertical LinearLayout. The nested LinearLayout serves no real purpose other than to slow down your UI performance.

To avoid including such a redundant view group, you can instead use the element as the root view for the re-usable layout. For example:

Now, when you include this layout in another layout (using the tag), the system ignores the element and places the two buttons directly in the layout, in place of the tag.

Комментировать
268 просмотров
Комментариев нет, будьте первым кто его оставит

Это интересно
No Image Компьютеры
0 комментариев
No Image Компьютеры
0 комментариев
No Image Компьютеры
180 комментариев
Adblock
detector