溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

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

發(fā)布時間:2023-02-22 09:59:00 來源:億速云 閱讀:119 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹了Android源碼分析onResume方法中獲取不到View寬高的相關(guān)知識,內(nèi)容詳細(xì)易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇Android源碼分析onResume方法中獲取不到View寬高文章都會有所收獲,下面我們一起來看看吧。

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

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

還要弄清楚Activity的生命周期。

另外布局都是通過setContentView(int)方法設(shè)置的,所以弄清楚setContentView的流程也很重要。

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

    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ……
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = appContext.getClassLoader();
          // 【關(guān)鍵點(diǎn)1】通過反射加載一個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)部會初始化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對象,并且調(diào)用了onCreate方法。

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

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

    @Override
    public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
            String reason) {
        ……
        // 【關(guān)鍵點(diǎn)1】performResumeActivity 中會調(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è)置不可見
            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】在這里,開始做View的add操作
                    wm.addView(decor, l); 
                } else {
                    ……
                    a.onWindowAttributesChanged(l);
                }
            }

            
        } else if (!willBeVisible) {
           ……
        }
       ……
    }

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

  • 調(diào)用performResumeActivity, 該方法中r.activity.performResume(r.startsNotResumed, reason);會調(diào)用Activity的onResume方法。

  • 執(zhí)行完Activity的onResume后調(diào)用了wm.addView(decor, l);,到這里,開始將此前創(chuàng)建的DecorView添加到視圖中,也就是在這之后才開始布局的繪制流程

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

問題2、為什么View.post為什么可以獲取View寬高?

那接下來我們開始看第二個問題,先看看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);
        }

        // 加入到這個View的消息隊(duì)列中
        getRunQueue().post(action);
        return true;
    }

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

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

接下來我們看一下mAttachInfo在什么時機(jī)才會賦值。

View.java

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

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

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

不要問為什么一定是這個,因?yàn)槲铱催^,哈哈哈

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

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

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

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

但還沒結(jié)束,我們post出去的任務(wù),什么時候執(zhí)行呢,上面host可以看成是根布局,一個ViewGroup,通過一層一層的分發(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;
    }
}

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

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

關(guān)于“Android源碼分析onResume方法中獲取不到View寬高”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“Android源碼分析onResume方法中獲取不到View寬高”知識都有一定的了解,大家如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI