Android优化程序性能的小技巧

1,不要在嵌套的布局文件中设置多余的Background,因为系统绘制布局需要消耗一定的性能


2,当一些需要不停变化状态的View不出现在当前屏幕不可见的时候,就让它停止变化,比如一些图片的轮播,当它不可见的时候,就停止轮播


3,尽量减少布局的嵌套,因为布局的嵌套层级越深,布局渲染的时间就越久,复杂的布局尽量考虑使用RelativeLayout相对布局来减少嵌套,简单的布局就尽量使用LinearLayout,因为相对于RelativeLayout,前者消耗的性能比较小


4,当使用include引用布局的时候,被引用的布局如果可以,就尽量使用merge 标签

<LinearLayout xmlns: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">  
  
    <include layout="@layout/titlebar"/>  
  
    <TextView android:layout_width=”match_parent”  
              android:layout_height="wrap_content"  
              android:text="@string/hello"  
              android:padding="10dp" />  
  
    ...  
  
</LinearLayout>  

titlebar的布局文件应该是这样

<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>  
因为父布局本来就是一个LinearLayout垂直布局,子布局titlebar的两个按钮Button也是按照垂直布局,就没有必要在子布局中再用LinearLayout,使用merge标签就能让子布局融入父布局,这样就减少了布局的一个嵌套

5,需要的时候使用ViewStub标签,ViewStub的最大好处就是可以当你需要的时候才会加载,使用他并不会影响Ui初始化的性能,像嵌套在界面中的正在加载界面,加载错误界面,可以使用ViewStub,以减少内存使用量,加快渲染速度

<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" />  
当我们需要使用这个布局的时候,可以这样实例化

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

ViewStub只能inflate一次,因为inflate的时候是将其指向的布局文件解析inflate并替换当前ViewStub本身(体现了ViewStub占位符的性质),一旦替换,此时原来布局文件中就没有ViewStub控件了,see android 中关于布局文件延迟加载控件ViewStub


待续...




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值