Android 布局优化 -- 学习笔记

通过一些惯用、有效的布局原则,我们可以制作出加载效率高并且复用性高的UI。简单来说,在Android UI布局过程中,需要遵守的原则包括如下几点:

  • 尽量多使用RelativeLayout,不要使用绝对布局AbsoluteLayout;
  • 将可复用的组件抽取出来并通过< include />标签使用;
  • 使用< ViewStub />标签来加载一些不常用的布局;
  • 使用< merge />标签减少布局的嵌套层次;

1. <include /> 这个比较简单就不进行深入讨论了低吗如下:

<include /> 用layout属性引入了一个布局。

<?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="match_parent" >
 
    <ListView
        android:id="@+id/simple_list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
 
    <include layout="@layout/foot.xml" />
 
</RelativeLayout>

foot.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="match_parent" >
 
    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dp_40"
        android:layout_above="@+id/text"/>
 
    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dp_40"
        android:layout_alignParentBottom="true"
        android:text="@string/app_name" />
 
</RelativeLayout>

<include />还是比较简单的。

2.<merge  />

< merge />标签的作用是合并UI布局,使用该标签能降低UI布局的嵌套层次。该布局的应用场景有两个、

  • 当xml文件的根布局是FrameLayout时,可以用merge作为根节点。
  • 是当用include标签导入一个共用布局时,如果父布局和子布局根节点为同一类型,可以使用merge将子节点布局的内容合并包含到父布局中,这样就可以减少一级嵌套层次。

3.<ViewStub />

viewstub标签同include标签一样可以用来引入一个外部布局,不同的是,viewstub引入的布局默认不会扩张,即既不会占用显示也不会占用位置,从而在解析layout时节省cpu和内存。

可以理解为不加载布局,用的是和在加载。

用 inflate() 方式展开。

ViewStub stub = (ViewStub)findViewById(R.id.network_error_layout);
networkErrorView = stub.inflate();

用其他形式展开

View viewStub = findViewById(R.id.network_error_layout);
viewStub.setVisibility(View.VISIBLE);   // ViewStub被展开后的布局所替换
networkErrorView =  findViewById(R.id.network_error_layout); // 获取展开后的布局

参考下面文章写的,大家可以去看详细的解释

详细请参考 http://www.infoq.com/cn/articles/android-optimise-layout

详细请参考 http://www.trinea.cn/android/layout-performance/

原文地址:https://www.cnblogs.com/youngKen/p/4831489.html