使用include包含公共布局
就像在C或者JAVA中,可以将重复的代码段写成子函数调用;在XML中,对于重复的布局也可以写在单独的文件中,然后用<inclulde>
来“调用”。
例如自定义了一个标题栏common_title_bar.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#484E61" >
<ImageButton
android:id="@+id/switch_city"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:background="@drawable/ic_home_white_24dp" />
<TextView
android:id="@+id/city_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textColor="#fff"
android:textSize="24sp" />
<ImageButton
android:id="@+id/refresh_weather"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:background="@drawable/ic_refresh_white_24dp" />
</RelativeLayout>
在其他的布局中,可以使用<include>
标签包含这个标题栏:
<include layout="@layout/common_title_bar" />
使用merge合并布局
使用<merge>
标签可以避免过度嵌套。
例如,公共布局使用的是垂直方向的LinearLayout
,而主布局使用的也是垂直方向的LinearLayout
,那么,在主布局include这个公共布局的时候,就会出现两个LinearLayout
相互嵌套,而内层的LinearLayout
没有发挥任何作用,反而降低了效率。这时候就可以使用<merge>
作为公共布局的根元素,这样在include的时候就会自动忽略根元素,避免了嵌套。
<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>
使用ViewStub动态加载布局
如果有一部分布局很少用到,可以使用<ViewStub>
标签,在需要的时候再将布局加载到内存中,这样可以大大减少对内存的占用。
在<ViewStub>
标签中,可以使用android:layout
指定需要加载的布局。例如需要动态加载一个透明的进度条:
<ViewStub
android:id="@+id/stub_import"
android:inflatedId="@+id/panel_import"
android:layout="@layout/progress_overlay"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom" />
在代码中加载的方法有两种:
- 使用
setVisibility(View.VISIBLE)
方法 - 调用
inflate()
方法
((ViewStub) findViewById(R.id.stub_import)).setVisibility(View.VISIBLE);
// or
View importPanel = ((ViewStub) findViewById(R.id.stub_import)).inflate();
注意,inflate()
方法直接返回了加载的布局,所以不需要再调用findViewById()
的方法。