《50 Android Hacks》学习心得一:延迟加载和布局重用
来源:互联网 发布:java分布式框架搭建 编辑:程序博客网 时间:2024/06/03 17:30
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 0
- 《50 Android Hacks》学习心得一:延迟加载和布局重用
- 《50 Android Hacks》学习心得二:自定义ViewGroup
- Android ViewStub 布局延迟加载
- 布局文件延迟加载
- 布局文件延迟加载
- mybatis的延迟加载和一、二级缓存
- Android中关于布局文件延迟加载控件ViewStub
- Android中关于布局文件延迟加载控件ViewStub
- Android布局封装重用:iniclude和merge的使用
- 使用 ViewStub 延迟加载布局
- android 延迟加载动作
- android app 延迟加载
- 50 Android hacks(hack 1)
- 50 Android Hacks(hack 2)
- 50 Android Hacks(hack 14)
- 50 Android hacks(hack15)
- 延迟加载和动态加载
- 异步加载和延迟加载
- 【CSS】前端笔试题总结
- iOS调试奇巧淫技(一)
- Trick(十二)——统计 label(序列)各个标签值出现的次数以及出现次数最多的标签
- oracle数据库问题
- ARM MMU工作原理剖析
- 《50 Android Hacks》学习心得一:延迟加载和布局重用
- golangStart fetch.go
- iOS -- pch文件介绍 及用法 - $(SRCROOT)/工程名/pch文件名.pch -- <一>
- iOS开发~CocoaPods使用详细说明
- 使用docker 构建一个web应用
- jQuery学习笔记——选择器
- adplus使用
- 算法训练 和为T
- 带排序去重的list