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

學無先后,達者為師

網站首頁 編程語言 正文

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

作者:小小范同學 ? 更新時間: 2023-05-30 編程語言

前言

有一個經典的問題,我們在Activity的onCreate中可以獲取View的寬高嗎?onResume中呢?

對于這類八股問題,只要看過都能很容易得出答案:不能。

緊跟著追問一個,那為什么View.post為什么可以獲取View寬高?

今天來看看這些問題,到底為何?

今日份問題:

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

基于Android API 29版本。

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

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

還要弄清楚Activity的生命周期,關于Activity的啟動流程,后面單獨寫一篇,本文會帶一部分。

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

首先要知道Activity的生命周期都在ActivityThread中, 當我們調用startActivity時,最終會走到ActivityThread中的performLaunchActivity

    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ……
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = appContext.getClassLoader();
          // 【關鍵點1】通過反射加載一個Activity
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
           ……
        } catch (Exception e) {
            ……
        }
        try {
            ……
            if (activity != null) {
                ……
                // 【關鍵點2】調用attach方法,內部會初始化Window相關信息
                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()) {
                  // 【關鍵點3】調用Activity的onCreate方法
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                ……
            }
            ……
        return activity;
    }

performLaunchActivity中主要是創建了Activity對象,并且調用了onCreate方法。

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

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

    @Override
    public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
            String reason) {
        ……
        // 【關鍵點1】performResumeActivity 中會調用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); // 設置不可見
            ViewManager wm = a.getWindowManager();
            WindowManager.LayoutParams l = r.window.getAttributes();
            a.mDecor = decor;
            ……
            if (a.mVisibleFromClient) {
                if (!a.mWindowAdded) {
                    a.mWindowAdded = true;
                  // 【關鍵點2】在這里,開始做View的add操作
                    wm.addView(decor, l); 
                } else {
                    ……
                    a.onWindowAttributesChanged(l);
                }
            }
        } else if (!willBeVisible) {
           ……
        }
       ……
    }

handleResumeActivity中兩個關鍵點

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

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

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

那接下來我們開始看第二個問題,先看看View.post的實現。

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

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

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

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

View.java

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

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

不要問為什么一定是這個,因為我看過,哈哈哈

其實ViewRootImpl就是一個布局管理器,這里面有很多內容,可以多看看。

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

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

再強調一遍,這個方法很長,內部很多信息,但其實總結來看,就是View的繪制流程,上面的【關鍵點2、3、4】。也就是這個方法執行完成之后,我們就能拿到View的寬高了;到這里,我們終于看到和View的寬高相關的東西了。

但還沒結束,我們post出去的任務,什么時候執行呢,上面host可以看成是根布局,一個ViewGroup,通過一層一層的分發,最后我們看看View的dispatchAttachedToWindow方法。

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

這里可以看到調用了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,轉移到mAttachInfo中的Handler, 等待接下來的調用執行。

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

結論

  • onCreate和onResume中無法獲取View的寬高,是因為還沒執行View的繪制流程。
  • view.post之所以能夠拿到寬高,是因為在繪制之前,會將獲取寬高的任務放到Handler的消息隊列,等到View的繪制結束之后,便會執行。

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

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新