布局重用<include/>
include可以将UI分离成可重复利用的组件,提高代码的重复利用率!
例如:所有布局都需要一个统一样式的标题栏,那么我们就可以把,这个标题用include来实现重复利用。
以下为标题栏的layout文件titlebar.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width=”match_parent”
android:layout_height="wrap_content"
android:background="@color/titlebar_bg">
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/gafricalogo" />
</FrameLayout>
那么在那三四个activity中你可以适用Include标记
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:gravity="center_horizontal">
<include layout="@layout/titlebar"/>
<TextView android:layout_width=”match_parent”
android:layout_height="wrap_content"
android:text="@string/hello" />
...
</LinearLayout>
上面的include调用多套了一个FrameLayout根节点,在构造图式时会浪费cpu资源,我们可以通过merge来解决这个问题。
则标题栏的布局titlebar2.xml:
减少布局层次<merge/>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/gafricalogo" />
</merge>
这样形成的布局文件就少了一个外层点root节点,在使用include调用时,会直接忽略merge。减少cpu资源的浪费。
因此<merge/>与<include/>标签通常的一起使用。
注意,使用include标签调用的布局,一些RelativeLayout属性是没办法使用的。
需要时重用 <ViewStub/>
ViewStub标签,尽管<include/>的使用会提高统一样式组建的重复使用率,但是某些使用的很少的布局控件(例如错误提示栏)
尽管不显示(设置为View.Gone),这些ui控件在整个布局被加载时仍然会被创建实例,仍然会対cpu造成浪费,影响视图的绘制速
度。ViewStub则解决这个问题。
ViewStub的状态为View.GONE不会占用布局空间 ViewStub将会被引用到UI的外部布局。(ViewStub内部不支持merge标签)
有了ViewStub后,你需要它的时候可见,占用布局空间。不需要它时就不占用布局空间,这样就提高了UI的绘制速度,但是当
ViewStub显示出来后,就不能整体隐藏了释放内存了。
<span style="font-size:14px;"><ViewStub
android:id="@+id/view_stub"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inflatedId="@+id/sub"
android:layout="@layout/sub"/>
</span>
ViewStub的三种状态都对布局有不同的影响:
View.VISIBLE:视图对用户可见,并且会占据布局的空间。
VIew.INVISIBLE:视图对用户不可见,但是会占用布局的空间。
View.GONE:视图对用户不可见也不会占用布局空间。
要想扩张用ViewStub引用外部布局,可以自己扩张它或者改变它的可见性:
((ViewStub)findViewById(R.id.view_stub)).setVisibility(View.VISIABLE);
有一点需要记住的是:当ViewStub inflate后,这个ViewStub就从View层次中移除了。因此,没有必要保留一个对ViewStub的引用(如在类的字段里)。