• Best Practices for Performance_3.Improving Layout Performance 优化布局


    http://developer.android.com/training/improving-layouts/index.html

    1. 优化布局层次

    1)  每增加一个View或者布局,都会增加额外的 “初始化-布局-重绘” 的时间。 LinearLayout 嵌套会导致层次较多,特别是如果设置了 layout_weight 属性时,效率会很低,因为每个子View都会measure两次。这在View需要重复创建,比如ListView或者Gridview中影响会比较明显。可以用RelativeLayout来减少层次。

    浅而宽的层次好过窄而深的层次。最大层次最好不要超过10层。

    2) 使用hierarchyviewer 分析和优化布局效率

    目录: <sdk>/tools/hierarchyviewer

    Load View Hierarchy -> 加载一个界面的布局树

    选中一个元素,会显示其 Measure、Layout、Draw 三个过程的时间,三个红绿灯的颜色代表前面三个过程的效率。

    3)使用 Lint 来优化布局。

    在 ADT 16+ 的版本上已经集成了 Lint 工具,Eclipse工具栏上有相应的图标。它会给出很多优化的建议。

    目录: <sdk>/tools/lint.bat

    旧版本中使用的是 layoutopt 工具。

    2. 使用 <include/>、<merge/>标签

    1)使用<include/>复用布局

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

    可以重新指定布局的属性:

    <include android:id=”@+id/news_title”         
    android:layout_width=”match_parent”
    android:layout_height=”match_parent” layout=”@layout/titlebar”/>

    但是要让重新指定的布局属性起作用,必须同时指定 layout_width 和 layout_height 属性。

    2) include 布局的时候,某些情况下使用<merge/>标签,可以减少一层布局。

    3. 使用 ViewStub 来延迟布局加载

    某些View或者布局很少用到,可以在需要的时候才加载,以便减少内存使用,提高绘制效率。

    ViewStub 是很轻量级的View,没有尺寸,不会绘制,布局inflate的时候也不消耗什么性能。

    eg:

    <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" />

    在需要使用该View的时候:

    ((ViewStub) findViewById(R.id.stub_import)).setVisibility(View.VISIBLE); 
    
    // 或者 View importPanel = ((ViewStub) findViewById(R.id.stub_import)).inflate();

    ViewStub 一旦 visible/inflated 后它就不在有效,被替换成 layout指定的布局,其id也失效。

    新布局的id是 inflatedId 指定的。

    ViewStub 现在不支持 <merge/> 标签。

     

    4. 让ListView滑动顺畅

    1)关键是把耗时操作放到工作线程中,不要放在UI线程。
    2)使用ViewHolder

  • 相关阅读:
    百度地图之自动提示--autoComplete
    h5之scrollIntoView控制页面元素滚动
    angular之interceptors拦截器
    angular之$broadcast、$emit、$on传值
    前端基础入门(一)-HTML-HTML基础
    改进自定义博客
    自定义博客主题
    使用JavaScript策略模式校验表单
    【经典面试题】圣杯布局以及双飞翼布局原理
    [JavaScript设计模式]惰性单例模式
  • 原文地址:https://www.cnblogs.com/zijianlu/p/3628391.html
Copyright © 2020-2023  润新知