现在的位置: 首页 > 综合 > 正文

【layout】Android中merge和include标签的使用

2017年12月05日 ⁄ 综合 ⁄ 共 2108字 ⁄ 字号 评论关闭

先说下<merge />标签的第一个比较简单的用法。如果我们使用FrameLayout作为activity's content view的父元素(也就是在main.xml里把它写在最外层),那么可以考虑用<merge />替换<FrameLayout />标签。官方文档给出的解释是这样做可以减少一级布局层次达到优化布局的效果。

这是文档里关于这部分结论的原文,个人E文水平有限,直接贴出来好了:

Obviously, using <merge /> works in this case because the parent of an activity's content view is always a FrameLayout. You could not apply this trick if your layout was using a LinearLayout as its root tag for instance.

关于merge标签include标签的使用,直接用实例说明吧。

TestMergeInclude.java

public class TestMergeInclude extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
	}
}

main.xml

OkCancelBar.java

public class OkCancelBar extends LinearLayout {

	public OkCancelBar(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	public OkCancelBar(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub

		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();
	}
}

okcancelbar.xml

okcancelbar_button.xml

一点思考:

1、在OkCancelBar类的构造器中,我们看到一段稍微复杂点的代码。其实它们并不难,只是通过ID拿到某个特定的Button引用,然后为其设定要显示出来的文字。与直接使用android:text相比,这种设置要累赘得多。所以不妨把这个累赘看成是为利用<merge />的优点所付出的代价。这个优点就是组件重用,我们只在okcancelbar_button.xml文件里声明了一个Button,但在使用时却拥有了两个(当然可以更多)Button。

2、这里可重用组件(这里的okcancelbar_button)的定义很关键,因为它关联着所有要使用它的功能点。比如:如果你确定在你的应用里,所有使用到这个button的地方需要的显示文字都一样,那你就可以在上面button的定义中再加一个android:text属性,这样就省去了使用时再去逐个设置的麻烦。另外,本例的okcancelbar_button里只定义了一个button,我想这里应该可以扩展到一个布局单元,比如LinearLayout,FrameLayout等等之类的。本人还没尝试,值得一做。

3、关于使用<merge />标签的一些限制:
(1)它只能作为XML布局声明的root元素来使用;
(2)使用它来inflate一个布局时,必须指定一个ViewGroup实例作为其父元素并且设置attachToRoot属性为true(参考 inflate(int, android.view.ViewGroup, boolean) 方法的说明 )。

抱歉!评论已关闭.