android性能优化笔记,UI篇

下面是项目中优化重构时一些心得,陆续会补全

1. 减少UI层级

1.1 减少不必要的层级
<LinearLayout 
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:background="#ffffff">

       <net.xuele.xuelets.ui.widget.custom.ResourceView
        android:id="@+id/resourse_content"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</LinearLayout>

外面那层布局可以删掉,修改后如下

<net.xuele.xuelets.ui.widget.custom.ResourceView    
      xmlns:android="http://schemas.android.com/apk/res/android"   
      android:id="@+id/resourse_content"    
      android:layout_width="wrap_content"   
      android:layout_height="wrap_content" 
      android:background="#ffffff"
/>
1.2:善用<merge>减少布局层级

android的布局xml文件,需要一个顶级容器来容纳子节点,使用merge标签代替顶级容器,可以减少一层UI嵌套。

比如有个自定义的控件ResourceView,继承自RelativeLayout
xml文件如下,RelativeLayout就是顶级容器

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout  
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"  
    android:layout_height="match_parent">  
     <ImageView     
       android:layout_width="match_parent"   
       android:layout_height="match_parent"    
       android:scaleType="fitXY"   
       android:src="@mipmap/yso"/>
</RelativeLayout>

此时我们使用<merge>标签代替<RelativeLayout>作为顶级容器时,表示不指定子节点ImageView的顶级容器,ImageView将被直接添加到ResourceView里。

减少UI层级优化结果

经过1.1、1.2优化之后,布局文件减少了两个层级。


before.jpg
after.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容