Android布局优化 html
• 1、优化布局层次结构 android
• 避免布局嵌套,此外几个嵌套的LinearLayout实例使用layout_weight参数会致使两次测量,特别是重复的添加,好比ListView、GridView。避免layout_weight sql
• 一、检查你的布局 网络
• 经过tools/hierarchyviewer.bat找到布局性能瓶颈。 app
• 二、修改你的布局 布局
Measure: 0.598ms 性能
Layout: 0.110ms 优化
Draw: 2.146ms 线程
• 三、使用Lint检查(几个例子) xml
• LinearLayout保护一个imageview和textView可使用一个控件来实现。 textView属性android:drawableLeft="@drawable/up“
• 如根标签仅做为跟布局(无背景等),使用<merge>替代。在代码中inflate一个以merge为根元素的布局文件时候,你须要指定一个ViewGroup 做为其容器,而且要设置attachToRoot 为true
• 删除没子控件、没背景的布局
• 若是一个layout只有子控件,没有兄弟控件,而且不是一个ScrollView或者根节点,并且没有设置背景,那么咱们能够移除这个父控件,直接把子控件提高为父控件。
• 尽可能减小内嵌的层级,考虑使用更多平级的组件 RelativeLayout or GridLayout来提高布局性能,默认最大的深度是10
• 2、复用布局<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标签减小无用的布局
• <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>
• 3、动态加载视图
• 有时候咱们须要复杂的视图且少用,咱们能够按须要的时候装载以便减小内存,提升体验。原来咱们都是设置在布局中,而后使用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/>
• 4、平滑滚动ListView
• 一、使用后台线程操做IO/网络/sql Access
• 二、为了在listView中减小findView操做,把row设置成ViewHolder
static class ViewHolder {
TextView text;
TextView timestamp;
ImageView icon;
ProgressBar progress;
int position;
}