基本的優(yōu)化總結(jié)(四)

導(dǎo)言

這節(jié)主要是講一下布局方面關(guān)于UI的優(yōu)化手段燃领,屬于編碼中的一些細(xì)節(jié)處理

UI流暢性優(yōu)化

先看Systrace中的某一幀


Systrace中的某一幀

從Alert提示中我們也可以知道反饋的是測量和布局時間過久猛蔽,所以說后續(xù)要做的就是優(yōu)化測量和布局的時間

ViewStub

先看一下ViewStub里面的一些關(guān)鍵代碼

    public ViewStub(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context);

        final TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.ViewStub, defStyleAttr, defStyleRes);
        mInflatedId = a.getResourceId(R.styleable.ViewStub_inflatedId, NO_ID);
        mLayoutResource = a.getResourceId(R.styleable.ViewStub_layout, 0);
        mID = a.getResourceId(R.styleable.ViewStub_id, NO_ID);
        a.recycle();
        //可以看到颠焦,默認(rèn)是不顯示的
        setVisibility(GONE);
        setWillNotDraw(true);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //默認(rèn)的大小也是0朴上,并且不會有任何測量操作
        setMeasuredDimension(0, 0);
    }

    @Override
    public void draw(Canvas canvas) {
        //本身并不會繪制任何東西  
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
      //同樣的也不會要求別人繪制任何東西
    }

從上面我們可以看出,實際上ViewStub就是一個占位容器,本身不會做任何操作她按,并且測量的時候默認(rèn)為GONE的視圖并不會參與測量
再看setVisibility方法

    @Override
    @android.view.RemotableViewMethod(asyncImpl = "setVisibilityAsync")
    public void setVisibility(int visibility) {
        if (mInflatedViewRef != null) {
            //如果內(nèi)部布局已經(jīng)inflate過,那么直接顯示或者隱藏
            View view = mInflatedViewRef.get();
            if (view != null) {
                view.setVisibility(visibility);
            } else {
                throw new IllegalStateException("setVisibility called on un-referenced view");
            }
        } else {
            //否則顯示自己比勉,然后再進(jìn)行inflate操作
            super.setVisibility(visibility);
            if (visibility == VISIBLE || visibility == INVISIBLE) {
                inflate();
            }
        }
    }

    public View inflate() {
        final ViewParent viewParent = getParent();

        if (viewParent != null && viewParent instanceof ViewGroup) {
            if (mLayoutResource != 0) {
                final ViewGroup parent = (ViewGroup) viewParent;
                final View view = inflateViewNoAdd(parent);
                replaceSelfWithView(view, parent);

                mInflatedViewRef = new WeakReference<>(view);
                if (mInflateListener != null) {
                    mInflateListener.onInflate(this, view);
                }

                return view;
            } else {
                throw new IllegalArgumentException("ViewStub must have a valid layoutResource");
            }
        } else {
            throw new IllegalStateException("ViewStub must have a non-null ViewGroup viewParent");
        }
    }

    private View inflateViewNoAdd(ViewGroup parent) {
        final LayoutInflater factory;
        if (mInflater != null) {
            factory = mInflater;
        } else {
            factory = LayoutInflater.from(mContext);
        }
        //這里才進(jìn)行ViewStub內(nèi)的布局的inflate操作
        final View view = factory.inflate(mLayoutResource, parent, false);

        if (mInflatedId != NO_ID) {
            view.setId(mInflatedId);
        }
        return view;
    }

    private void replaceSelfWithView(View view, ViewGroup parent) {
        final int index = parent.indexOfChild(this);
        //將當(dāng)前ViewStub從父布局中移除
        parent.removeViewInLayout(this);
        //然后將ViewStub內(nèi)的布局直接添加到父布局中
        final ViewGroup.LayoutParams layoutParams = getLayoutParams();
        if (layoutParams != null) {
            parent.addView(view, index, layoutParams);
        } else {
            parent.addView(view, index);
        }
    }

看完之后我們就清楚了清钥,相比于直接把視圖放入xml中,ViewStub一開始并不會直接進(jìn)行inflate操作后众,而是等到手動調(diào)用inflate或者setVisibility(View.VISIBLE)距帅,也就是說在ViewStub中的layout的inflate被延遲處理了

結(jié)論:ViewStub的使用場景就是一個視圖需要滿足一定條件的情況下才顯示,此時該視圖就應(yīng)該通過ViewStub修飾,通過延遲加載的方式來優(yōu)化原始原來布局的測量等速度恩敌,因為這個布局不一定可見

布局優(yōu)化

我們知道Android的測量是從頂層布局開始然后一直向下分發(fā)恢口,所謂布局優(yōu)化,實際上就是降低inflate和測量/布局的耗時,比方說對比于RelativeLayout和LinearLayout,先看一個布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="text1"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="text2"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="text3"
            />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="text4"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="text5"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="text6"
            />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="text7"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="text8"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="text9"
            />

    </LinearLayout>

</LinearLayout>
inflate的情況(不包括系統(tǒng)布局)
測量和布局的耗時

然后看一下直接使用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">

    <TextView
        android:id="@+id/tv_text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text1"
        />

    <TextView
        android:id="@+id/tv_text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text2"
        android:layout_toRightOf="@+id/tv_text1"
        />

    <TextView
        android:id="@+id/tv_text3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text3"
        android:layout_toRightOf="@+id/tv_text2"
        />

    <TextView
        android:id="@+id/tv_text4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text4"
        android:layout_below="@+id/tv_text1"
        />

    <TextView
        android:id="@+id/tv_text5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text5"
        android:layout_toRightOf="@+id/tv_text4"
        android:layout_below="@+id/tv_text1"
        />

    <TextView
        android:id="@+id/tv_text6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text6"
        android:layout_toRightOf="@+id/tv_text5"
        android:layout_below="@+id/tv_text1"
        />

    <TextView
        android:id="@+id/tv_text7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text7"
        android:layout_below="@+id/tv_text4"
        />

    <TextView
        android:id="@+id/tv_text8"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text8"
        android:layout_toRightOf="@+id/tv_text7"
        android:layout_below="@+id/tv_text4"
        />

    <TextView
        android:id="@+id/tv_text9"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text9"
        android:layout_toRightOf="@+id/tv_text8"
        android:layout_below="@+id/tv_text4"
        />

</RelativeLayout>
inflate的情況(不包括系統(tǒng)布局)

測量和布局的耗時

大致分析一下差別,其實可以看出蜜另,如果在同樣的實現(xiàn)效果下鹅很,使用RelativeLayout可以減少視圖的個數(shù)整袁,從而優(yōu)化inflate的效率绳匀,相對于測量和布局來說痹仙,這個比較明顯
當(dāng)然例子中的布局層級比較簡單,所以說沒有看出measure/layout上面的差別,當(dāng)布局特別復(fù)雜的時候脚乡,這個也是要考慮的部分

結(jié)論:
優(yōu)先應(yīng)該考慮降低布局的層級窒典,實際上也就是降低視圖的數(shù)量,這樣可以相對有效的降低inflate的耗時

merge

上面提到了要降低布局層級,實際開發(fā)中會出現(xiàn)一種情況,比方說setContentView浇冰,實際上父布局就是一個FrameLayout漂佩,如果此時我們的xml中父布局是FrameLayout

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/iv_image2"
        android:layout_width="36dp"
        android:layout_height="36dp"
        android:src="@mipmap/ic_launcher"
        android:layout_gravity="center"
        />

    <ImageView
        android:id="@+id/iv_image3"
        android:layout_width="36dp"
        android:layout_height="36dp"
        android:src="@mipmap/ic_launcher"
        android:layout_gravity="right"
        />

</FrameLayout>

此時想到于FrameLayout中嵌套FrameLayout,很明顯這個是多余咳榜,所幸的是Android提供了方式來處理氯夷,可以通過merge標(biāo)簽來合并

<?xml version="1.0" encoding="utf-8"?>
<merge
    xmlns:android="http://schemas.android.com/apk/res/android">

    <ImageView
        android:id="@+id/iv_image2"
        android:layout_width="36dp"
        android:layout_height="36dp"
        android:src="@mipmap/ic_launcher"
        android:layout_gravity="center"
        />

    <ImageView
        android:id="@+id/iv_image3"
        android:layout_width="36dp"
        android:layout_height="36dp"
        android:src="@mipmap/ic_launcher"
        android:layout_gravity="right"
        />

</merge>

看一下LayoutInflate的具體處理

    ...
    if (TAG_MERGE.equals(name)) {
        if (root == null || !attachToRoot) {
            throw new InflateException("<merge /> can be used only with a valid "
                                + "ViewGroup root and attachToRoot=true");
            }

            rInflate(parser, root, inflaterContext, attrs, false);
            } else {
    ...

可以看到這里直接進(jìn)入rInflate,實際上就是繼續(xù)解析一下標(biāo)簽,也就是說inflate遇到merge之后就直接pass攀圈,然后把內(nèi)部的視圖添加到merge外部的視圖當(dāng)中

測量優(yōu)化

我們知道視圖在使用的時候必須要進(jìn)行測量,具體的意義就是要確定子視圖的大小球凰,那么這一塊的耗時也會影響到一幀的流暢性甩挫,也應(yīng)該是優(yōu)化考慮的一部分
比方說LinearLayout和RelativeLayout,最明顯的區(qū)別就是LinearLayout對內(nèi)部的子視圖只測量一次,而RelativeLayout要對內(nèi)部的子視圖測量兩次,所以說測量的速度上面來說LinearLayout會優(yōu)于RelativeLayout攻走,布局的話因為RelativeLayout在測量的時候就計算好了子視圖的位置,所以相對LinearLayout來說可能會快一點(diǎn)。

結(jié)論:
從使用的角度來說,如果可以單一的使用LinearLayout或者RelativeLayout的話確實是比較好的選擇,否則可以考慮通過自定義視圖的方式來實現(xiàn)測量和布局,自己實現(xiàn)可以避免了大量的無意義的計算操作拭卿,效率會更好

總結(jié)

UI這塊的優(yōu)化相對比較復(fù)雜勺鸦,具體的情況還是要做深入的分析,個人認(rèn)為原則上就是盡量降低視圖層級辫继,能自己寫一個ViewGroup直接擺好的那就最好舵变,如果時間充裕的話熙兔,也可以考慮通過Systrace來進(jìn)行對比,選擇合理方案泻拦,這一節(jié)講了視圖層級優(yōu)化闹瞧,下一節(jié)看看具體的工具

文章系列:
基本的優(yōu)化總結(jié)(一)
基本的優(yōu)化總結(jié)(二)
基本的優(yōu)化總結(jié)(三)
基本的優(yōu)化總結(jié)(四)
基本的優(yōu)化總結(jié)(五)
基本的優(yōu)化總結(jié)(六)
基本的優(yōu)化總結(jié)(七)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末通殃,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子霹购,更是在濱河造成了極大的恐慌齐疙,老刑警劉巖轿塔,帶你破解...
    沈念sama閱讀 219,427評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件癌蚁,死亡現(xiàn)場離奇詭異复唤,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)呈宇,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,551評論 3 395
  • 文/潘曉璐 我一進(jìn)店門好爬,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人甥啄,你說我怎么就攤上這事存炮。” “怎么了蜈漓?”我有些...
    開封第一講書人閱讀 165,747評論 0 356
  • 文/不壞的土叔 我叫張陵穆桂,是天一觀的道長。 經(jīng)常有香客問我融虽,道長享完,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,939評論 1 295
  • 正文 為了忘掉前任有额,我火速辦了婚禮驼侠,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘谆吴。我一直安慰自己,他們只是感情好苛预,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,955評論 6 392
  • 文/花漫 我一把揭開白布句狼。 她就那樣靜靜地躺著,像睡著了一般热某。 火紅的嫁衣襯著肌膚如雪腻菇。 梳的紋絲不亂的頭發(fā)上胳螟,一...
    開封第一講書人閱讀 51,737評論 1 305
  • 那天,我揣著相機(jī)與錄音筹吐,去河邊找鬼糖耸。 笑死,一個胖子當(dāng)著我的面吹牛丘薛,可吹牛的內(nèi)容都是我干的嘉竟。 我是一名探鬼主播,決...
    沈念sama閱讀 40,448評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼洋侨,長吁一口氣:“原來是場噩夢啊……” “哼舍扰!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起希坚,我...
    開封第一講書人閱讀 39,352評論 0 276
  • 序言:老撾萬榮一對情侶失蹤边苹,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后裁僧,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體个束,經(jīng)...
    沈念sama閱讀 45,834評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,992評論 3 338
  • 正文 我和宋清朗相戀三年聊疲,在試婚紗的時候發(fā)現(xiàn)自己被綠了茬底。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,133評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡售睹,死狀恐怖桩警,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情昌妹,我是刑警寧澤捶枢,帶...
    沈念sama閱讀 35,815評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站飞崖,受9級特大地震影響烂叔,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜固歪,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,477評論 3 331
  • 文/蒙蒙 一蒜鸡、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧牢裳,春花似錦逢防、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,022評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至判帮,卻和暖如春局嘁,著一層夾襖步出監(jiān)牢的瞬間溉箕,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,147評論 1 272
  • 我被黑心中介騙來泰國打工悦昵, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留肴茄,地道東北人。 一個月前我還...
    沈念sama閱讀 48,398評論 3 373
  • 正文 我出身青樓但指,卻偏偏與公主長得像寡痰,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子枚赡,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,077評論 2 355

推薦閱讀更多精彩內(nèi)容