《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
原创粉丝点击