日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Android嵌套線性布局玩法坑解決方法_Android

作者:打哭廖廖 ? 更新時間: 2022-12-04 編程語言

前言

嵌套線性布局大家應該都用的非常熟悉,畢竟這玩意理解起來也是真的簡單,而且如果熟悉的話這玩意開發起來的效率也是真的快,不用一下一下拖動。

但是這個玩意有個非常的問題,就是性能問題,而且人家性能問題是指數級別增加的,怎么回事呢,因為你如果一層一層的嵌套布局的話,系統在繪制的時候就是指數級別的繪制次數,如果你只是嵌套了倆層那都還能接受的玩,如果你一個界面控件很多,然后你又嵌套幾層線性布局,那這個時候性能就十分低下了。

詳解

  • 看下面的代碼,就是一個十分典型的線性嵌套布局,用起來是很爽,無腦套,但是系統可不少受
<?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中是很常見的

所以我們的嵌套對性能影響是指數級別的,比如線性套線性套線性這種。

原文鏈接:https://juejin.cn/post/7160309137471963149

欄目分類
最近更新