Android嵌套线性布局玩法坑解决方法
前言
嵌套线性布局大家应该都用的非常熟悉,毕竟这玩意理解起来也是真的简单,而且如果熟悉的话这玩意开发起来的效率也是真的快,不用一下一下拖动。
但是这个玩意有个非常的问题,就是性能问题,而且人家性能问题是指数级别增加的,怎么回事呢,因为你如果一层一层的嵌套布局的话,系统在绘制的时候就是指数级别的绘制次数,如果你只是嵌套了俩层那都还能接受的玩,如果你一个界面控件很多,然后你又嵌套几层线性布局,那这个时候性能就十分低下了。
详解
- 看下面的代码,就是一个十分典型的线性嵌套布局,用起来是很爽,无脑套,但是系统可不少受
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> </LinearLayout> </LinearLayout> </LinearLayout> </LinearLayout> </LinearLayout> </FrameLayout>
为什么会让性能降低的怎么严重呢?
结论是绘制次数太多,主要是线性布局会造成这个问题,线性布局会对子view进行二次测量甚至三次测量。
比如:
1.LinearLayout宽度为wrap_content,因此它将选择子View的最大宽度为其最后的宽度
2.但是有个子View的宽度为match_parent,意思它将以LinearLayout的宽度为宽度,这就陷入死循环了
3.因此这时候, LinearLayout 就会先以0为强制宽度测量一下子View,并正常地测量剩下的其他子View,然后再用其他子View里最宽的那个的宽度,二次测量这个match_parent的子 View,最终得出它的尺寸,并把这个宽度作为自己最终的宽度。
4.这是对单个子View的二次测量,如果有多个子View写了match_parent ,那就需要对它们每一个都进行二次测量。
5.除此之外,如果在LinearLayout中使用了weight会导致测量3次甚至更多,重复测量在Android中是很常见的
所以我们的嵌套对性能影响是指数级别的,比如线性套线性套线性这种。
以上就是Android嵌套线性布局玩法坑解决方法的详细内容,更多关于Android 嵌套线性布局的资料请关注脚本之家其它相关文章!
相关文章
Android音视频开发之MediaExtactor使用教程
MediaExtactor在Android音视频开发中负责提取音视频信息和数据流的功能,可以通过该类实现从多媒体文件中剥离得到音频和视频的能力。本文将详细为大家介绍一下它的使用,感兴趣的可以了解一下2022-04-04基于startActivityForResult方法处理两个Activity之间数据传递问题
这篇文章主要介绍了基于startActivityForResult方法处理两个Activity之间数据传递问题的相关资料,需要的朋友可以参考下2015-11-11Android 老生常谈LayoutInflater的新认知
今天不想去聊一些Android的新功能,新特性之类的东西,特别想聊一聊这个老生常谈的话题:LayoutInflater,感兴趣的朋友来看看吧2022-03-03
最新评论