android--Merge和include标签的区别和使用
原文摘自:http://www.cnblogs.com/travelfromandroid/articles/2133206.html
使用
如果在一个项目中需要用到相同的布局设计,可以通过
在Android layout文件中需要一个顶级容器来容纳其他的组件,而不能直接放置多个组件。
单独将<merge />标签做个介绍,是因为它在优化UI结构时起到很重要的作用。目的是通过删减多余或者额外的层级,从而优化整个Android Layout的结构。
新的代码中,TextView和ImageView都直接添加到上一层的FrameLayout里。虽然视觉上看起来一样,但View的层次更加简单了:
很显然,在这个场合使用
<merge
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:okCancelBar="http://schemas.android.com/apk/res/com.example.android.merge">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="center"
android:src="@drawable/golden_gate" />
<com.example.android.merge.OkCancelBar
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:paddingTop="8dip"
android:gravity="center_horizontal"
android:background="#AA000000"
okCancelBar:okLabel="Save"
okCancelBar:cancelLabel="Don't save" />
</merge>
新的布局效果如下图所示:
OkCancelBar的代码很简单,因为这两个按钮在外部的XML文件中定义,通过LayoutInflate类导入。如下面的代码片段所示,R.layout.okcancelbar以OkCancelBar为父元素:
public class OkCancelBar extends LinearLayout {
public OkCancelBar(Context context, AttributeSet attrs) {
super(context, attrs);
setOrientation(HORIZONTAL);
setGravity(Gravity.CENTER);
setWeightSum(1.0f);
LayoutInflater.from(context).inflate(R.layout.okcancelbar, this, true);
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.OkCancelBar, 0, 0);
String text = array.getString(R.styleable.OkCancelBar_okLabel);
if (text == null) text = "Ok";
((Button) findViewById(R.id.okcancelbar_ok)).setText(text);
text = array.getString(R.styleable.OkCancelBar_cancelLabel);
if (text == null) text = "Cancel";
((Button) findViewById(R.id.okcancelbar_cancel)).setText(text);
array.recycle();
}
}
两个按钮的定义如下面的XML所示。正如你所看到的,我们使用
<merge xmlns:android="http://schemas.android.com/apk/res/android">
<include
layout="@layout/okcancelbar_button"
android:id="@+id/okcancelbar_ok" />
<include
layout="@layout/okcancelbar_button"
android:id="@+id/okcancelbar_cancel" />
</merge>
我们创建了一个灵活且易于维护的自定义View,它有着高效的View层次:
·
· 当Inflate以
还没有评论,来说两句吧...