• 延迟加载与避免重复


    目标

    • 在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/  

  • 相关阅读:
    asp.net在线压缩和解压缩的实现 VS2005
    Office组件配置
    您无权查看或编辑目前 F:\XXX 的权限设置;但是,您可以取得所有权或更改审核设置
    23条心灵寄语献给在创业一线的兄弟姐妹
    IIS 环境下 w3wp.exe 进程 CPU 占用过高的解决方案
    SQLServer修改表所有者
    走出软件作坊推荐
    Asp.net 的 服务器推技术 (Server Push)
    上海火车站售票点
    Newtonsoft.Json.dll 本地调用正常,服务器调用不正常
  • 原文地址:https://www.cnblogs.com/zhjsll/p/4113671.html
Copyright © 2020-2023  润新知