android UI性能优化(2)--高性能界面布局

来源:互联网 发布:数控车设计图和编程 编辑:程序博客网 时间:2024/05/17 05:50

Ø在LinearLayout中慎用layout_weight(绘制2次);
Ø减少布局的层次;
Ø去除不用的布局或者是累赘的的父控件;
Ø去除不用或者是累赘的的父控件;
Ø使用compound drawables;
Ø使用include,merge,ViewStub 标签;
Ø背景的优化(NinePatch省内存,透明优化绘制);
Øinvalidate()->onDraw(),减少invalidate次数;

layout_weight:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"   android:orientation="horizontal"   android:layout_width="fill_parent"   android:layout_height="fill_parent"    ><Buttonandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_weight="1"android:text="Button1"/><Button android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_weight="2"android:text="Button2"/></LinearLayout>

Ø假设屏幕宽度为X
第一次:button1的measuredWidth为X,button2也为X (因为用了weight,所以linearLayout每次measure child时不考虑前一个已经占用的大小),total_width为2X
第二次:计算delta=x-total_width=-x,然后会将button1的宽度设为
x+delta*1/3=0.66x, button2的宽度为 x+delta*2/3=0.33x

Ø上面布局是否还有其它问题?
Ø为什么说android:layout_width="0dp"

   或者android:layout_height=“0dp”更高效?

compound drawables:

xml:   <TextView    android: layout_width = "wrap_content"    android: layout_height = "wrap_content" 
   android: text = "@ string/text"    android: drawableTop = "@drawable/ic_launcher"    android: gravity = "center"代码:   TextView tv = (TextView) findViewById (R.id.textView); tv.setCompoundDrawablesWithIntrinsicBounds (0, R.drawable.ic_launcher, 0, 0);

背景优化:

public void onCreate(Bundle icicle){    super.onCreate(icicle);       
   setContentView(R.layout.mainview); getWindow().setBackgroundDrawable(null);    ...}   <resources>   <style name="NoBackgroundTheme" parent="android:Theme">    <item name="android:windowBackground">@null   </item>   </style>   </resources

加载背景使用theme:<resources>    <style name=“Theme.Shelves”    parent=“android:Theme”>        <item name=“android:windowBackground”>@drawable/background_app</item>        <item name=“android:windowNoTitle”>true</item>    </style></resources>(不会从默认背景过来闪一下,速度更快,内存消耗降低)

Ø避免在onDraw()的过程中去做大量的创建对象和内存分配;
Ø 尽量用invalidate (int l,int t, int r, int b)方法去替代 invalidate ()方法;
Ø尽量减少requestLayout()的执行时间->层次布局越浅则越好;
Ø有条件使用setLayerType:LAYER_TYPE_HARDWARE,其它情况则使用LAYER_TYPE_NONE;

Ø提供的背景图片正好和视图的大小一致
Ø背景图片预先缩放,减少缩放次数。

ØListView的每一行的item布局顶层标签尽量使用相对布局而不是线性布局,可以减少布局的层次;
ØalignWithParentIfMissing的使用;



原创粉丝点击