欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android源碼解析onResume方法中獲取不到View寬高

 更新時(shí)間:2023年02月22日 09:48:59   作者:小小范同學(xué)  
這篇文章主要為大家介紹了Android源碼解析onResume方法中獲取不到View寬高示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

前言

有一個(gè)經(jīng)典的問(wèn)題,我們?cè)贏(yíng)ctivity的onCreate中可以獲取View的寬高嗎?onResume中呢?

對(duì)于這類(lèi)八股問(wèn)題,只要看過(guò)都能很容易得出答案:不能。

緊跟著追問(wèn)一個(gè),那為什么View.post為什么可以獲取View寬高?

今天來(lái)看看這些問(wèn)題,到底為何?

今日份問(wèn)題:

  • 為什么onCreate和onResume中獲取不到view的寬高?
  • 為什么View.post為什么可以獲取View寬高?

基于A(yíng)ndroid API 29版本。

問(wèn)題1、為什么onCreate和onResume中獲取不到view的寬高?

首先我們清楚,要拿到View的寬高,那么View的繪制流程(measure—layout—draw)至少要完成measure,【記住這一點(diǎn)】。

還要弄清楚Activity的生命周期,關(guān)于A(yíng)ctivity的啟動(dòng)流程,后面單獨(dú)寫(xiě)一篇,本文會(huì)帶一部分。

另外布局都是通過(guò)setContentView(int)方法設(shè)置的,所以弄清楚setContentView的流程也很重要,后面也補(bǔ)一篇。

首先要知道Activity的生命周期都在ActivityThread中, 當(dāng)我們調(diào)用startActivity時(shí),最終會(huì)走到ActivityThread中的performLaunchActivity

    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ……
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = appContext.getClassLoader();
          // 【關(guān)鍵點(diǎn)1】通過(guò)反射加載一個(gè)Activity
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
           ……
        } catch (Exception e) {
            ……
        }
        try {
            ……
            if (activity != null) {
                ……
                // 【關(guān)鍵點(diǎn)2】調(diào)用attach方法,內(nèi)部會(huì)初始化Window相關(guān)信息
                activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor, window, r.configCallback,
                        r.assistToken);
                ……
                if (r.isPersistable()) {
                  // 【關(guān)鍵點(diǎn)3】調(diào)用Activity的onCreate方法
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                ……
            }
            ……
        return activity;
    }

performLaunchActivity中主要是創(chuàng)建了Activity對(duì)象,并且調(diào)用了onCreate方法。

onCreate流程中的setContentView只是解析了xml,初始化了DecorView,創(chuàng)建了各個(gè)控件的對(duì)象;即將xml中的 轉(zhuǎn)化為一個(gè)TextView對(duì)象。并沒(méi)有啟動(dòng)View的繪制流程。

上面走完了onCreate,接下來(lái)看onResume生命周期,同樣是在ActivityThread中的performResumeActivity

    @Override
    public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
            String reason) {
        ……
        // 【關(guān)鍵點(diǎn)1】performResumeActivity 中會(huì)調(diào)用activity的onResume方法
        final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
        ……
        final Activity a = r.activity;
        ……
        if (r.window == null && !a.mFinished && willBeVisible) {
            r.window = r.activity.getWindow();
            View decor = r.window.getDecorView();
            decor.setVisibility(View.INVISIBLE); // 設(shè)置不可見(jiàn)
            ViewManager wm = a.getWindowManager();
            WindowManager.LayoutParams l = r.window.getAttributes();
            a.mDecor = decor;
            ……
            if (a.mVisibleFromClient) {
                if (!a.mWindowAdded) {
                    a.mWindowAdded = true;
                  // 【關(guān)鍵點(diǎn)2】在這里,開(kāi)始做View的add操作
                    wm.addView(decor, l); 
                } else {
                    ……
                    a.onWindowAttributesChanged(l);
                }
            }
        } else if (!willBeVisible) {
           ……
        }
       ……
    }

handleResumeActivity中兩個(gè)關(guān)鍵點(diǎn)

  • 調(diào)用performResumeActivity, 該方法中r.activity.performResume(r.startsNotResumed, reason);會(huì)調(diào)用Activity的onResume方法。
  • 執(zhí)行完Activity的onResume后調(diào)用了wm.addView(decor, l);,到這里,開(kāi)始將此前創(chuàng)建的DecorView添加到視圖中,也就是在這之后才開(kāi)始布局的繪制流程

到這里,我們應(yīng)該就能理解,為何onCreate和onResume中無(wú)法獲取View的寬高了,一句話(huà)就是:View的繪制要晚于onResume。

問(wèn)題2、為什么View.post為什么可以獲取View寬高?

那接下來(lái)我們開(kāi)始看第二個(gè)問(wèn)題,先看看View.post的實(shí)現(xiàn)。

    public boolean post(Runnable action) {
        final AttachInfo attachInfo = mAttachInfo;
        // 添加到AttachInfo的Handler消息隊(duì)列中
        if (attachInfo != null) {
            return attachInfo.mHandler.post(action);
        }
        // 加入到這個(gè)View的消息隊(duì)列中
        getRunQueue().post(action);
        return true;
    }

post方法中,首先判斷attachInfo成員變量是否為空,如果不為空,則直接加入到對(duì)應(yīng)的Handler消息隊(duì)列中。否則走getRunQueue().post(action);

從Attach字面意思來(lái)理解,其實(shí)就可以知道,當(dāng)View執(zhí)行attach時(shí),才會(huì)拿到mAttachInfo, 因此我們?cè)趏nResume或者onCreate中調(diào)用view.post(),其實(shí)走的是getRunQueue().post(action)。

接下來(lái)我們看一下mAttachInfo在什么時(shí)機(jī)才會(huì)賦值。

View.java

void dispatchAttachedToWindow(AttachInfo info, int visibility) {
    mAttachInfo = info;
}

dispatch相信大家都不會(huì)陌生,分發(fā);那么一定是從根布局上開(kāi)始分發(fā)的,我們可以全局搜索,可以看到

不要問(wèn)為什么一定是這個(gè),因?yàn)槲铱催^(guò),哈哈哈

其實(shí)ViewRootImpl就是一個(gè)布局管理器,這里面有很多內(nèi)容,可以多看看。

ViewRootImpl中直接定位到performTraversals方法中;這個(gè)方法一定要了解,而且特別長(zhǎng),下面我抽取幾個(gè)關(guān)鍵點(diǎn)。

    private void performTraversals() {
      ……
      // 【關(guān)鍵點(diǎn)1】分發(fā)mAttachInfo
      host.dispatchAttachedToWindow(mAttachInfo, 0);
      ……
      //【關(guān)鍵點(diǎn)2】開(kāi)始測(cè)量
      performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
      ……
      //【關(guān)鍵點(diǎn)3】開(kāi)始布局
      performLayout(lp, mWidth, mHeight);
      ……
      // 【關(guān)鍵點(diǎn)4】開(kāi)始繪制
      performDraw();
      ……
    }

再?gòu)?qiáng)調(diào)一遍,這個(gè)方法很長(zhǎng),內(nèi)部很多信息,但其實(shí)總結(jié)來(lái)看,就是View的繪制流程,上面的【關(guān)鍵點(diǎn)2、3、4】。也就是這個(gè)方法執(zhí)行完成之后,我們就能拿到View的寬高了;到這里,我們終于看到和View的寬高相關(guān)的東西了。

但還沒(méi)結(jié)束,我們post出去的任務(wù),什么時(shí)候執(zhí)行呢,上面host可以看成是根布局,一個(gè)ViewGroup,通過(guò)一層一層的分發(fā),最后我們看看View的dispatchAttachedToWindow方法。

 void dispatchAttachedToWindow(AttachInfo info, int visibility) {
     mAttachInfo = info;
     ……
     // Transfer all pending runnables.
     if (mRunQueue != null) {
         mRunQueue.executeActions(info.mHandler);
         mRunQueue = null;
     }
}

這里可以看到調(diào)用了mRunQueue.executeActions(info.mHandler);

public void executeActions(Handler handler) {
    synchronized (this) {
        final HandlerAction[] actions = mActions;
        for (int i = 0, count = mCount; i < count; i++) {
            final HandlerAction handlerAction = actions[i];
            handler.postDelayed(handlerAction.action, handlerAction.delay);
        }
        mActions = null;
        mCount = 0;
    }
}

這就很簡(jiǎn)單了,就是將post中的Runnable,轉(zhuǎn)移到mAttachInfo中的Handler, 等待接下來(lái)的調(diào)用執(zhí)行。

這里要結(jié)合Handler的消息機(jī)制,我們post到Handler中的消息,并不是立刻執(zhí)行,不要認(rèn)為我們是先dispatchAttachedToWindow的,后執(zhí)行的測(cè)量和繪制,就沒(méi)辦法拿到寬高。實(shí)則不是,我們只是將Runnable放到了handler的消息隊(duì)列,然后繼續(xù)執(zhí)行后面的內(nèi)容,也就是繪制流程,結(jié)束后,下一個(gè)主線(xiàn)程任務(wù)才會(huì)去取Handler中的消息,并執(zhí)行。

結(jié)論

  • onCreate和onResume中無(wú)法獲取View的寬高,是因?yàn)檫€沒(méi)執(zhí)行View的繪制流程。
  • view.post之所以能夠拿到寬高,是因?yàn)樵诶L制之前,會(huì)將獲取寬高的任務(wù)放到Handler的消息隊(duì)列,等到View的繪制結(jié)束之后,便會(huì)執(zhí)行。

以上就是Android源碼解析onResume方法中獲取不到View寬高的詳細(xì)內(nèi)容,更多關(guān)于A(yíng)ndroid onResume獲取不到View寬高的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論