Android性能优化之布局优化
来源:互联网 发布:ps4 神之浩劫网络差 编辑:程序博客网 时间:2024/06/01 14:32
布局优化的思想很简单,就是尽量减少布局文件的层级,这个道理是很浅显的,布局中的层级少了,这就意味着Android绘制时的工作量少了,那么程序的性能自然就高了。
如何进行布局优化呢?
首先删除布局中无用的控件和层级,其次有选择地使用性能较低的ViewGroup,如:布局中既可以使用LinearLayout也可以使用RelativeLayout,那么就采用LinearLayout,这是因为相对布局的功能比较复杂,它的布局过程需要花费更多的CPU时间。
另一种手段就是采用include标签,merge标签和ViewStub。
include标签
可以将一个指定的布局文件加载到当前的布局文件中。如下:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <include layout="@layout/title_bar"/> <TextView android:id="@+id/first_btn" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/rect_color_primary" android:gravity="center" android:padding="@dimen/item_spacing" android:text="FirstExample" android:textColor="@color/colorPrimaryDark"/> ...</LinearLayout>
需要注意的是,如果include标签指定了layout_*这种属性,那么要求
android:layout_width和android:layout_height必须存在,否则其他的android:layout_*形式的属性无法生效。
merge标签
一般和include标签一起使用从而减少布局的层级。在上述示例中,由于当前布局是一个竖直方向的LinearLayout,用过merge标签就可以去掉多余的那一层LinearLayout。如下:
<merge xmlns:android="http://schemas.android.com/apk/res/android"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="button1"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="button2"/></merge>
ViewStub
ViewStub继承了View,它非常轻量级且宽和高都是0,因此它本身不参与任何的布局和绘制过程。比如:网络异常时的界面,这个时候就没有必要在整个界面初始化将其加进来,通过ViewStub就可以做到在使用的时候再加载,提高了程序初始化的性能:
<ViewStub android:id="@+id/stub_import" android:inflatedId="@+id/panel_import" android:layout="@layout/layout_empty_txt" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom"/>
panel_import是@layout/layout_empty_txt这个布局的根元素的id。
在需要加载ViewStub中的布局时,可以按照如下两种方式:
(ViewStub)findViewById(R.id.stub_import).setVisibility(View.VISIBLE);
或者
View mImportPanel = ((ViewStub)findViewById(R.id.stub_import)).inflate();
通过上述两个方法加载后,ViewStub就会被它内部的布局替换掉,这个时候ViewStub就不再是整个布局结构中的一部分了。
- android 性能优化之布局
- Android性能优化之布局优化
- Android性能优化之布局优化
- Android性能优化之布局优化
- 性能优化之Android布局优化
- android性能优化之布局优化
- Android性能优化之布局优化
- Android性能优化之布局优化篇
- Android性能优化之布局优化
- Android性能优化之布局优化篇
- android性能优化之布局优化
- Android性能优化之布局优化总结
- Android性能优化之布局优化
- 10.1Android性能优化之布局优化
- android 性能优化之布局优化-----ViewStub
- Android性能优化之布局优化
- Android性能优化之布局优化
- Android性能优化之布局优化
- C/C++学习的50个经典网站
- ZKProgressHUD iOS 易于使用的 HUD
- AJRW错误AA707
- Python爬虫爬取美剧网站
- ListMultimap分组统计
- Android性能优化之布局优化
- BZOJF2306 [Ctsc2011]幸福路径
- java网络编程
- linux历史
- 栈的压入、弹出序列
- Android属性动画完全解析(中),ValueAnimator和ObjectAnimator的高级用法
- oracle 存储过程学习
- noi-8176-验证子串
- 《ACM程序设计》书中题目 J