Android布局优化
Android布局优化
• 一、优化布局层次结构
• 避免布局嵌套,此外几个嵌套的LinearLayout实例使用layout_weight参数会导致两次测量,特别是重复的添加,比如ListView、GridView。避免layout_weight
• 1、检查你的布局
• 通过tools/hierarchyviewer.bat找到布局性能瓶颈。
• 2、修改你的布局
Measure: 0.598ms
Layout: 0.110ms
Draw: 2.146ms
• 3、使用Lint检查(几个例子)
• LinearLayout保护一个imageview和textView可以使用一个控件来实现。 textView属性android:drawableLeft="@drawable/up“
• 如根标签仅作为跟布局(无背景等),使用<merge>替代。在代码中inflate一个以merge为根元素的布局文件时候,你需要指定一个ViewGroup 作为其容器,并且要设置attachToRoot 为true
• 删除没子控件、没背景的布局
• 如果一个layout只有子控件,没有兄弟控件,并且不是一个ScrollView或者根节点,而且没有设置背景,那么我们可以移除这个父控件,直接把子控件提升为父控件。
• 尽量减少内嵌的层级,考虑使用更多平级的组件RelativeLayoutorGridLayout来提升布局性能,默认最大的深度是10
• 二、复用布局<include/>
• 创建可重用的layout组件
• 使用定义的组件<includelayout="@layout/titlebar"/>
• <FrameLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width=”match_parent”android:layout_height="wrap_content"android:background="@color/titlebar_bg"> <ImageViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/gafricalogo" /> </FrameLayout>
• <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical" android:layout_width=”match_parent”android:layout_height=”match_parent”android:background="@color/app_bg"android:gravity="center_horizontal"><includelayout="@layout/titlebar"/><TextViewandroid:layout_width=”match_parent”android:layout_height="wrap_content"android:text="@string/hello" android:padding="10dp"/> </LinearLayout>
• <include android:id=”@+id/news_title”android:layout_width=”match_parent” android:layout_height=”match_parent”layout=”@layout/title”/>
• 使用merge标签减少无用的布局
•<mergexmlns: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>
• 三、动态加载视图
• 有时候我们需要复杂的视图且少用,我们可以按需要的时候装载以便减少内存,提高体验。原来我们都是设置在布局中,然后使用View.GONE属性,但是好资源影响性能。ViewStub是一个轻量级的View,它一个看不见的,不占布局位置,占用资源非常小的控件
• 定义ViewStub
<ViewStubandroid: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" />
• 装载布局
((ViewStub)findViewById(R.id.stub_import)).setVisibility(View.VISIBLE); // or ViewimportPanel = ((ViewStub) findViewById(R.id.stub_import)).inflate();
Inflate只能访问一次,通过inflatedId找到布局。
缺点:使用的布局不支持<merge/>
• 四、平滑滚动ListView
• 1、使用后台线程操作IO/网络/sql Access
• 2、为了在listView中减少findView操作,把row设置成ViewHolder
staticclassViewHolder{
TextViewtext;
TextViewtimestamp;
ImageViewicon;
ProgressBarprogress;
intposition;
}
更多相关文章
- android中gps的使用以及解析nmea0183协议
- 系出名门Android(7) - 控件(View)之ZoomControls, Include...
- ubuntu 14.04 adb 配置及使用
- Android(安卓)编程下 Touch 事件的分发和消费机制
- Android中使用httpclient等小结
- android:imeOptions 标签
- 箭头函数的基础使用
- NPM 和webpack 的基础使用
- Python list sort方法的具体使用