Android 布局文件的性能--使用include标签重用Layout---转

Re-using Layouts with <include/>

尽管Android提供了很多种小的组件可以重用,我们还需要自定义一些稍微复杂一点的小组件进行重用。我们可以使用<include/> and <merge/> 标签来对当前的layout嵌入一些其他的layout.

在创建一个稍微复杂一点的layout时,重用layout是个很给力的方法。比如我们需要一个YES/NO的控制栏,包含文字提示的Progress bar。这意味着我们可以在很多地方重用那些自定义的layout.
Create a Re-usable Layout [创建一个可重用的Layout]
如果你已经知道哪些组件是会重用的,我们可以创建一个XML并且定义这个layout。
例如:下面定义了一个需要在每个Activity都需要显示的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>


Use the <include> Tag [使用<include>标签]
下面示例了一个包含了titlebar控件的布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:background="@color/app_bg"
android:gravity="center_horizontal">

<include layout="@layout/titlebar"/>

<TextView android:layout_width=”match_parent”
android:layout_height="wrap_content"
android:text="@string/hello"
android:padding="10dp" />

...

</LinearLayout>

我们可以重写任何include里面的属性,例如:
<include android:id=”@+id/news_title”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
layout=”@layout/title”/>

Use the <merge> Tag [使用<merge>标签]
某些时候,自定义可重用的布局包含了过多的层级标签,比如我们需要在LinearLayout里面嵌入一个重用的组件,而恰恰这个自定义的可重用的组件根节点也是LinearLayout,这样就多了一层没有用的嵌套,无疑这样只会拖慢程序速度。而这个时候如果我们使用merge根标签就可以避免那样的问题。
例如:
<merge xmlns:android="http://schemas.android.com/apk/res/android">

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/add"/>

<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/delete"/>

</merge>
这样的话,使用<include>包含上面的布局的时候,系统会自动忽略merge层级,而把两个button直接放置与include平级。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值