欢迎访问移动开发之家(rcyd.net),关注移动开发教程。移动开发之家  移动开发问答|  每日更新
页面位置 : > > > 内容正文

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

来源: 开发者 投稿于  被查看 22505 次 评论:248

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 嵌套线性布局的资料请关注3672js教程其它相关文章!

您可能感兴趣的文章:
  • Android嵌套滚动和协调滚动的多种实现方法
  • Android深入探究自定义View之嵌套滑动的实现
  • 如何在Flutter中嵌套Android布局
  • Android线性布局与相对布局的实现
  • Android UI组件LinearLayout线性布局详解
  • Android手机开发 使用线性布局和相对布局实现Button垂直水平居中

用户评论