在写布局文件的时候,巧用这三个标签可以对布局进行优化
include
在开发过程中,不同页面里有相同的布局,我们可以将公用的布局提取成单独的layout文件,再使用<include>标签引入到使用它的页面布局文件里,从而实现布局的重用。
举例说明
被重用的布局文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是公用的布局" />
</RelativeLayout>
然后有一个布局中包含了这个布局,就可以这样用
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="@+id/container"
layout="@layout/include_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tv"
android:layout_marginTop="10dp" />
</RelativeLayout>
A t t e n t i o n \color{#FF0000}{Attention} Attention
- 两个地方都添加id的话,要保持一致,也可以只在一个地方添加id属性
- 两个地方的子元素的id一定不能一样
- 给include设置位置属性的话,必须同时设置宽高属性
merge
<merge>标签可用于减少视图层级来优化布局,减少布局的嵌套。
如果include标签的父布局和 include布局的根容器是相同类型的,那么根容器的可以使用merge代替
比如,上个例子中,被重用的布局和使用它的布局根容器都是RelativeLayout,这个时候被重用的布局的根容器就可以用merge代替。
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是公用的布局" />
</merge>
ViewStub
按需加载,需要的时候再去加载,不需要的时候可以不用加载,节约内存使用。通常情况我们会使用setVisibility方法来控制视图的显示和隐藏,但是这种情况视图已经加载了。
比如app中页面里某个布局只需要在特定的情况下才显示,其余情况下可以不用加载显示,这时候可以使用ViewStub。
需要注意的是 ViewStub的inflate()方法只能被调用一次,一旦调用后,ViewStub将从视图中移除,被对应的layout布局取代,同时会保留ViewStub上设置的属性效果。