安卓学习心得一:延迟加载和布局重用

1.1 使用<include />标签实现布局重用

我们可以通过<include />标签把在其他XML文件中定义的布局插入到当前布局文件中,从而避免在每个主要布局文件里都重复书写相同的控件或某一子布局代码,如果你正在创建一个复杂的布局或者布局文件变得很大,那么可以试试<include />

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <include layout="@layout/layout_second" />
</LinearLayout>
layout_second.xml布局文件如下:
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="100dp"
    android:background="@drawable/icon"
    android:padding="10dp"
    android:text="按钮" /

我们还可以在include标签里添加安卓控件的常见属性,例如:

<include
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_alignParentBottom="true"
    layout="@layout/activity_second" />
但是,前提是必须给这个<include />加上layout_width和layout_height属性,这两个属性的值将直接覆盖引用过来的layout的 layout_width和layout_height

1.2 使用ViewStub实现View的延时加载

设计布局时,某个视图可能暂时不想显示出来(或者隐藏),而想根据上下文或者用户交互情况,显示(隐藏)该视图。当然,你可以用setVisibility()来规定在某个时刻显示或者隐藏特定的视图,但是ViewStub是一种更优的选择。

ViewStub是一种不可见并且大小为0的视图,可以延迟到运行时填充(inflate)布局资源。当ViewStub设置为可视或者inflate()方法被调用后,就会填充布局资源,然后ViewStub便会被填充的视图替代。

 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="点击加载" />

    <ViewStub
        android:id="@+id/view_stub"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout="@layout/activity_second" />
</LinearLayout>
在代码中

ViewStub viewStub = (ViewStub)findViewById(R.id.view_stub);

然后在需要显示时,调用viewStub.inflate()或者viewStub..setVisibility(View.VISIBLE)可将视图显示出来

ViewStub的优点是activity或者fragment启动时不用一次性加载全部视图进来,从而优化了内存和加载速度


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序猫King

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值