布局优化的几种方法

使用include包含公共布局

就像在C或者JAVA中,可以将重复的代码段写成子函数调用;在XML中,对于重复的布局也可以写在单独的文件中,然后用<inclulde>来“调用”。
例如自定义了一个标题栏common_title_bar.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="#484E61" >

    <ImageButton
        android:id="@+id/switch_city"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_centerVertical="true"
        android:layout_marginLeft="10dp"
        android:background="@drawable/ic_home_white_24dp" />

    <TextView
        android:id="@+id/city_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textColor="#fff"
        android:textSize="24sp" />

    <ImageButton
        android:id="@+id/refresh_weather"
        android:layout_width="30dp"
        android:layout_height="30dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="10dp"
        android:background="@drawable/ic_refresh_white_24dp" />

</RelativeLayout>

在其他的布局中,可以使用<include>标签包含这个标题栏:

    <include layout="@layout/common_title_bar" />

使用merge合并布局

使用<merge>标签可以避免过度嵌套。
例如,公共布局使用的是垂直方向的LinearLayout,而主布局使用的也是垂直方向的LinearLayout,那么,在主布局include这个公共布局的时候,就会出现两个LinearLayout相互嵌套,而内层的LinearLayout没有发挥任何作用,反而降低了效率。这时候就可以使用<merge>作为公共布局的根元素,这样在include的时候就会自动忽略根元素,避免了嵌套。

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <Button
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
        android:text="@string/add"/>

    <Button
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
        android:text="@string/delete"/>

</merge>

使用ViewStub动态加载布局

如果有一部分布局很少用到,可以使用<ViewStub>标签,在需要的时候再将布局加载到内存中,这样可以大大减少对内存的占用。
<ViewStub>标签中,可以使用android:layout指定需要加载的布局。例如需要动态加载一个透明的进度条:

<ViewStub
    android:id="@+id/stub_import"
    android:inflatedId="@+id/panel_import"
    android:layout="@layout/progress_overlay"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom" />

在代码中加载的方法有两种:

  • 使用setVisibility(View.VISIBLE)方法
  • 调用inflate()方法
((ViewStub) findViewById(R.id.stub_import)).setVisibility(View.VISIBLE);
// or
View importPanel = ((ViewStub) findViewById(R.id.stub_import)).inflate();

注意,inflate()方法直接返回了加载的布局,所以不需要再调用findViewById()的方法。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值