Android嵌套线性布局玩法坑解决方法

Heather ·
更新时间:2024-09-20
· 1639 次阅读

目录

前言

详解

为什么会让性能降低的怎么严重呢?

前言

嵌套线性布局大家应该都用的非常熟悉,毕竟这玩意理解起来也是真的简单,而且如果熟悉的话这玩意开发起来的效率也是真的快,不用一下一下拖动。

但是这个玩意有个非常的问题,就是性能问题,而且人家性能问题是指数级别增加的,怎么回事呢,因为你如果一层一层的嵌套布局的话,系统在绘制的时候就是指数级别的绘制次数,如果你只是嵌套了俩层那都还能接受的玩,如果你一个界面控件很多,然后你又嵌套几层线性布局,那这个时候性能就十分低下了。

详解

看下面的代码,就是一个十分典型的线性嵌套布局,用起来是很爽,无脑套,但是系统可不少受

<?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

需要 登录 后方可回复, 如果你还没有账号请 注册新账号
相关文章