为了减轻UI绘制的负担,有必要把Layout编写的一些注意事项总结一下:
首先说一下< include/>,< merge/>,ViewStub的使用:
1、< include/>重用:
比如我们要写一个TitleBar(title_bar_layout.xml),是这样子的:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="50dp" android:orientation="horizontal"> <TextView android:layout_width="50dp" android:layout_height="match_parent" android:background="@drawable/back" /> <TextView android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:text="竞技台" android:textSize="18sp" /> <TextView android:layout_width="50dp" android:layout_height="match_parent" android:gravity="center" android:text="确定" android:textSize="18sp" /> </LinearLayout>
每一个界面中都有TitleBar,所以使用< include/>进行服用,以便统一管理,在使用的时候,一行代码就OK了。
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_layout_opt" android:layout_width="match_parent" android:layout_height="match_parent"> <include layout="@layout/title_bar_layout" /> </FrameLayout>
2、< merge/>减少视图层级:
为什么要减少视图层级,在加载布局的时候,inflater是通过深度优先遍历来构造视图树,每解析到一个View,就会递归调用inflater,直到这条路径的最后一个元素,然后再回溯过来将每一个View添加到他们的parent中,整个View树构建完毕。在使用了include后可能导致布局嵌套过多,出现不必要的layout节点,从而导致解析变慢。这个时候我们可以使用< merge/>标签。< merge/>标签可用于两种典型情况:
- 布局顶结点是FrameLayout且不需要设置background或padding等属性,可以用merge代替,因为Activity内容试图的parent view就是个FrameLayout,所以可以用merge消除只剩一个。
- 某布局作为子布局被其他布局include时,使用merge当作该布局的顶节点,这样在被引入时顶结点会自动被忽略,而将其子节点全部合并到主布局中。
3、ViewStub延迟加载:
延迟加载意味着我们可以分批次的将一个Layout中的View解析加载到内存,比如说,我们最先加载Loading的布局,等待网络请求,然后加载常规展示的布局,当网络请求发生错误或者空数据的时候,加载错误布局。分批次加载减轻了CPU和GPU的负担,ViewStub 是一个轻量的视图,不需要大小信息,也不会在被加入的 Layout 中绘制任何东西。ViewStub可见或是被inflate了,ViewStub就不存在了,取而代之的是被inflate的Layout。所以它也被称做惰性控件。
<?xml version="1.0" encoding="utf-8"?> <merge xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <include layout="@layout/title_bar_layout" /> <ViewStub android:inflatedId="@+id/no_data_view" android:id="@+id/no_data_view" android:layout="@layout/no_data_layout" android:layout_width="match_parent" android:layout_height="match_parent"/> </merge>
要让ViewStub显示出来,可以用viewStub.infalte()或viewStub.setVisibility(View.VISIBLE)来完成,如下。
public void showEmptyView() { // listview.setVisibility(View.GONE); if (mNoDataView == null) { ViewStub noDataViewStub = (ViewStub)findViewById(R.id.no_data_view); mNoDataView = noDataViewStub.inflate(); } else { mNoDataView.setVisibility(View.VISIBLE); } }
现在你可能会问,ViewStub和View.GONE的区别。他们的共同点是一开始的时候都不会显示,但是View.GONE在布局加载的时候,就已经添加到布局树上了,而ViewStub只会在显示的时候才会渲染布局。最后注意ViewStub加载的布局中不能有merge。
4、能用一个View搞定的,别用两个。