官术网_书友最值得收藏!

Linear and relative layout classes

The linear layout is relatively lightweight and very useful for layouts based on single rows or columns. However, more complex layouts require nesting layouts inside each other and this very quickly becomes resource hungry. Take a look at the following layout:

Nested linear layouts

The preceding layout was built using only linear layouts, as can be seen from the following Component Tree:

The component tree

Although perfectly workable and easy to understand, this layout is not as efficient as it could be. Even a single extra layer of layout nesting will have an impact on performance. Prior to the constraint layout, this problem was solved with the relative layout.

As the name suggests, the relative layout allows us to place screen components in relation to each other, using markup such as layout_toStartOf or layout_below. This allows us to flatten view hierarchies and the preceding layout could be recreated with just one single relative, root viewgroup. The following code demonstrates how the row of images in the previous layout can be generated without nesting any new layouts:

<ImageView 
android:id="@+id/image_header_1"
android:layout_width="128dp"
android:layout_height="128dp"
android:layout_alignParentStart="true"
android:layout_below="@+id/text_title"
app:srcCompat="@drawable/pizza_01" />

<ImageView
android:id="@+id/image_header_2"
android:layout_width="128dp"
android:layout_height="128dp"
android:layout_below="@+id/text_title"
android:layout_toEndOf="@+id/image_header_1"
app:srcCompat="@drawable/pizza_02" />

<ImageView
android:id="@+id/image_header_3"
android:layout_width="128dp"
android:layout_height="128dp"
android:layout_alignParentEnd="true"
android:layout_below="@+id/text_title"
app:srcCompat="@drawable/pizza_03" />

<ImageView
android:id="@+id/image_header_4"
android:layout_width="128dp"
android:layout_height="128dp"
android:layout_alignParentStart="true"
android:layout_below="@+id/text_title"
app:srcCompat="@drawable/pizza_04" />

Even if you are new to Android Studio, it is assumed that you will be familiar with linear and relative layouts. It is less likely that you will have encountered the constraint layout, which has been especially developed for Studio to alleviate the shortcomings of these older approaches.

In the previous examples, we used app:srcCompat as opposed to android:src. This is not strictly required here, but if we wished to apply any tinting to the image and hope to distribute the app for older Android versions, this choice will enable that.
主站蜘蛛池模板: 长顺县| 临泽县| 昌乐县| 达州市| 襄樊市| 道真| 五指山市| 兴文县| 南安市| 剑河县| 河津市| 雷州市| 满洲里市| 永平县| 宁晋县| 衡南县| 舟曲县| 通榆县| 凤庆县| 稷山县| 沁源县| 德化县| 蓬安县| 边坝县| 布拖县| 阿尔山市| 明溪县| 葫芦岛市| 周宁县| 铜川市| 望江县| 上蔡县| 佛山市| 玛沁县| 奉新县| 南澳县| 安溪县| 叶城县| 西林县| 广东省| 汉寿县|