HTML Diff
0 added 0 removed
Original 2026-01-01
Modified 2026-03-10
1 <p>Теги: android, merge, android developer, android-программирование, android studio, layout</p>
1 <p>Теги: android, merge, android developer, android-программирование, android studio, layout</p>
2 <p>Представим себе простую ситуацию - нам нужно создать вью, отражающий название компании и её рейтинг, и его мы будем пятьдесят раз использовать в приложении. Например, что-то вроде:</p>
2 <p>Представим себе простую ситуацию - нам нужно создать вью, отражающий название компании и её рейтинг, и его мы будем пятьдесят раз использовать в приложении. Например, что-то вроде:</p>
3 &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"&gt; &lt;ImageView android:id="@+id/rating" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="16dp" /&gt; &lt;TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;/LinearLayout&gt;<p>Теперь давайте создадим класс, его описывающий. Допустим, у нас будут два метода: один меняет картинку рейтинга в зависимости от значения, а другой задаёт имя:</p>
3 &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"&gt; &lt;ImageView android:id="@+id/rating" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="16dp" /&gt; &lt;TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;/LinearLayout&gt;<p>Теперь давайте создадим класс, его описывающий. Допустим, у нас будут два метода: один меняет картинку рейтинга в зависимости от значения, а другой задаёт имя:</p>
4 public class RatingView extends LinearLayout { private TextView nameView; private ImageView ratingView; public RatingView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); LayoutInflater.from(context).inflate(R.layout.name_view, this); ratingView = findViewById(R.id.rating); nameView = findViewById(R.id.name); } public void setRating(int rating) { switch (rating) { case 1: ratingView.setImageResource(R.drawable.one_star); break; case 2: ratingView.setImageResource(R.drawable.two_star); break; case 3: ratingView.setImageResource(R.drawable.three_star); break; } } public void setName(String value) { nameView.setText(value); } }<p>Отлично. Теперь давайте запихнём наш вью в лейаут активити:</p>
4 public class RatingView extends LinearLayout { private TextView nameView; private ImageView ratingView; public RatingView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); LayoutInflater.from(context).inflate(R.layout.name_view, this); ratingView = findViewById(R.id.rating); nameView = findViewById(R.id.name); } public void setRating(int rating) { switch (rating) { case 1: ratingView.setImageResource(R.drawable.one_star); break; case 2: ratingView.setImageResource(R.drawable.two_star); break; case 3: ratingView.setImageResource(R.drawable.three_star); break; } } public void setName(String value) { nameView.setText(value); } }<p>Отлично. Теперь давайте запихнём наш вью в лейаут активити:</p>
5 &lt;android.support.constraint.ConstraintLayout 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=".MainActivity"&gt; &lt;com.otus.merge.RatingView android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /&gt; &lt;/android.support.constraint.ConstraintLayout&gt;<p>Запустим приложение и заглянем в<strong>Tools &gt; Android &gt; Layout Inspector</strong>- посмотрим, что же у нас там такое:</p>
5 &lt;android.support.constraint.ConstraintLayout 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=".MainActivity"&gt; &lt;com.otus.merge.RatingView android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /&gt; &lt;/android.support.constraint.ConstraintLayout&gt;<p>Запустим приложение и заглянем в<strong>Tools &gt; Android &gt; Layout Inspector</strong>- посмотрим, что же у нас там такое:</p>
6 <p>Вот как выглядит наше дерево вью:</p>
6 <p>Вот как выглядит наше дерево вью:</p>
7 <p>Видим, что RatingView, расширяющий LinearLayout, содержит в себе ещё один LinearLayout, а внутри уже наши вьюшки. Теперь, используя<strong>&lt;merge&gt;</strong>, посмотрим, удастся ли нам исправить ситуацию:</p>
7 <p>Видим, что RatingView, расширяющий LinearLayout, содержит в себе ещё один LinearLayout, а внутри уже наши вьюшки. Теперь, используя<strong>&lt;merge&gt;</strong>, посмотрим, удастся ли нам исправить ситуацию:</p>
8 &lt;merge xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:parentTag="android.widget.LinearLayout" android:orientation="horizontal"&gt; &lt;ImageView android:id="@+id/rating" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="16dp" /&gt; &lt;TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;/merge&gt;<p>Запустили приложение. Идём в<strong>Tools &gt; Android &gt; Layout Inspector</strong>.</p>
8 &lt;merge xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:parentTag="android.widget.LinearLayout" android:orientation="horizontal"&gt; &lt;ImageView android:id="@+id/rating" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="16dp" /&gt; &lt;TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;/merge&gt;<p>Запустили приложение. Идём в<strong>Tools &gt; Android &gt; Layout Inspector</strong>.</p>
9 <p>И, ура!</p>
9 <p>И, ура!</p>
10 <p>Мы убрали лишний LinearLayout.</p>
10 <p>Мы убрали лишний LinearLayout.</p>
11 <h2>Делаем выводы</h2>
11 <h2>Делаем выводы</h2>
12 <p>Итак, для чего же был создан<strong>&lt;merge&gt;</strong>? Для<strong>оптимизации лейаутов</strong>путём уменьшения количества уровней в дереве вью. Когда LayoutInflater встречает этот тег, он пропускает его и добавляет дочерние элементы &lt;<strong>merge</strong>&gt; к родителю &lt;<strong>merge</strong>&gt;. Этот тег очень полезный и может использоваться во множестве ситуаций, а также он прекрасно комбинируется с &lt;<strong>include</strong>&gt;.</p>
12 <p>Итак, для чего же был создан<strong>&lt;merge&gt;</strong>? Для<strong>оптимизации лейаутов</strong>путём уменьшения количества уровней в дереве вью. Когда LayoutInflater встречает этот тег, он пропускает его и добавляет дочерние элементы &lt;<strong>merge</strong>&gt; к родителю &lt;<strong>merge</strong>&gt;. Этот тег очень полезный и может использоваться во множестве ситуаций, а также он прекрасно комбинируется с &lt;<strong>include</strong>&gt;.</p>
13 <p>Несколько моментов, которые нужно учитывать: - &lt;<strong>merge</strong>&gt; всегда должен быть корневым тегом; - в &lt;<strong>merge</strong>&gt; нужно обязательно указывать parentTag, как мы сделали в примере выше.</p>
13 <p>Несколько моментов, которые нужно учитывать: - &lt;<strong>merge</strong>&gt; всегда должен быть корневым тегом; - в &lt;<strong>merge</strong>&gt; нужно обязательно указывать parentTag, как мы сделали в примере выше.</p>
14 <p><em>Задать дополнительные вопросы по использованию &lt;<strong>merge</strong>&gt; всегда можно в комментариях.</em></p>
14 <p><em>Задать дополнительные вопросы по использованию &lt;<strong>merge</strong>&gt; всегда можно в комментариях.</em></p>
15  
15