延迟加载与避免重复

目标

  • 在xml布局文件中使用include标签来避免重复代码。
  • 使用ViewStub来实现View的延迟加载。

include

跟其他语言一样,我们通常会将在多个地方重复出现的代码提取到一个单独的文件中,然后再其他需要使用到的地方通过include引用该文件。如:

 1 <RelativeLayout

 2     xmlns:android="http://schemas.android.com/apk/res/android"

 3     android:layout_width="fill_parent"

 4     android:layout_height="fill_parent">

 5     <TextView

 6         android:layout_width="fill_parent"

 7         android:layout_height="wrap_content"

 8         android:layout_centerInParent="true"

 9         android:gravity="center_horizontal"

10         android:text="Hello"/>

11     <include layout="@layout/footer"/>

12 </RelativeLayout>

其中的footer.xml可能为:

1 <TextView xmlns:android="http://schemas.android.com/apk/res/android"

2     android:layout_width="fill_parent"

3     android:layout_height="wrap_content"

4     android:layout_alignParentBottom="true"

5     android:layout_marginBottom="30dp"

6     android:gravity="center_horizontal"

7     android:text="页脚"/>

注意,在footer.xml中我们使用到了RelativeLayout特有的属性layout_alignParentBottomh和layout_marginBottom,这将使得这个通用的布局文件不再通用,因为当父容器不是RelativeLayout时,layout_alignParentBottom明显无效,而且不知道会导致什么不可预知的效果。

如何解决这个问题?我们通常将跟特定布局有关的设置放在include标签中,如改进后的布局文件为:

 1 <RelativeLayout

 2     xmlns:android="http://schemas.android.com/apk/res/android"

 3     android:layout_width="fill_parent"

 4     android:layout_height="fill_parent">

 5     <TextView

 6         android:layout_width="fill_parent"

 7         android:layout_height="wrap_content"

 8         android:layout_centerInParent="true"

 9         android:gravity="center_horizontal"

10         android:text="Hello"/>

11     <include

12         layout="@layout/footer"

13         android:layout_width="fill_parent"

14         android:layout_height="wrap_content"

15         android:layout_alignParentBottom="true"

16         android:layout_marginBottom="30dp"/>

17 </RelativeLayout>

footer为:

1 <TextView xmlns:android="http://schemas.android.com/apk/res/android"

2     android:layout_width="0dp"

3     android:layout_height="0dp"

4     android:gravity="center"

5     android:text="页脚"/>

其中layout_width和layout_height设置为0是为了提醒用户覆盖这两个值,如果用户忽略也不会导致错误,只是footer不显示。

 

 

来源:http://inching.org/2013/12/31/android-hack2-lazy-loading-using-include/  

你可能感兴趣的:(延迟加载)