转在请注明出处: http://blog.youkuaiyun.com/liangrui_cust
在android当中使用include能够提高代码的重用性 , 这里以android的标题栏为例, 说明android中使用include重用布局带来的好处.
首先, 我们要写一个xml的布局文件, 这里谢了一个简单的title, 有返回和标题
<merge>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorTitle"
android:id="@+id/toolbar"
android:paddingRight="@dimen/margin_middle"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/tool_bar_img_back"
android:visibility="gone"
android:id="@+id/toolbar_back"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="@color/colorWhite"
android:id="@+id/toolbar_title"
android:text="title"
/>
</RelativeLayout>
</android.support.v7.widget.Toolbar>
</merge>
这里需要说明的是, 在布局的最外层, 使用merge标签 , merge标签 能够将其布局下面的布局进行优化, 减少无用的布局嵌套, 比如有两个以上的相同的linearLayout布局嵌套在一起, 则会被优化成一层或者更少的层级.
在使用include布局的时候, 实际上是在当前界面定义了一个framelayout, 将布局在中的内容加到这个framelayout中, 并没有直接加载到这个布局中来, 所以在使用findviewById的时候, 返回值是空 . 这时, 使用merge标签就能将这层framelayout布局优化掉 , 相当于直接在布局中加上include中的内容, 能够使用findviewbyId去查找.
写完了布局, 在activity中写出查找布局的方法, 因为这个栗子是标题栏, 每个activity都会有, 建议写在BaseActivity ,其他的activity去继承, 代码如下
public void initToolbar(){
mToolbar = (Toolbar) findViewById(R.id.toolbar);
}
public void initToolbar(String title){
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setToolbarTitle(title);
}
public void setToolbarTitle(String title) {
if (mToolbar != null){
mToolbarTitle = (TextView) mToolbar.findViewById(R.id.toolbar_title);
mToolbarTitle.setVisibility(View.VISIBLE);
mToolbarTitle.setText(title);
}
}
public String getToolbarTitle(){
String ret = null;
if (mToolbar != null && mToolbarTitle != null) {
ret = mToolbarTitle.getText().toString();
}
return ret;
}
public void enToolbarBack(View.OnClickListener listener){
if (mToolbar != null){
ImageView view = (ImageView) mToolbar.findViewById(R.id.toolbar_back);
view.setVisibility(View.VISIBLE);
view.setOnClickListener(listener);
}
}
使用的时候, 在onCreate 中调用
initToolbar();
setToolbarTitle("登录");
enToolbarBack(this);
使用这种方式 , 可以实现只有一个toolbar标题栏, 不同的activity可以显示不同的标题, 图片 , 按钮, 而不用去每个布局都写这么标题栏 .
这种方式也是有缺点的, 因为toolbar布局中的资源全都被加载到了界面中, 虽然有些是看不到的, 会耗费一些资源, 可以考虑加上一些其他的方式去处理 . 例如使用viewStub去进行优化 .