android_View.post(Runnable)在onCreate獲取控件寬高分析

問題的切入點

在實際開發(fā)過程中,我們有時候需要在 activity 中去獲取某一個 view 的高度,然后根據(jù)該獲取的高度去設(shè)置其他 view 的高度來達到我們的目的,往往我們都會在 activity#onCreate 直接去 調(diào)用 view#getHeight() 但是這個會管用嗎,能真正獲取到高度嗎?這些我們運行下面的實例,然后結(jié)合源碼的角度去分析這個結(jié)果。

代碼示例

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   
    final MyView myView = (MyView) findViewById(R.id.myview);
   
    int height = myView.getHeight();
    int width = myView.getWidth();
    Log.e("zeal", "第一次獲取myView height:" + height + ";width:" + width);
    myView.post(new Runnable() {
        @Override
        public void run() {
            int height = myView.getHeight();
            int width = myView.getWidth();
            Log.e("zeal", "第二次獲取myView height:" + height + ";width:" + width);
        }
    });
    height = myView.getHeight();
    width = myView.getWidth();
    Log.e("zeal", "第三次獲取myView height:" + height + ";width:" + width);
}
@Override
protected void onResume() {
    super.onResume();
    Log.e("zeal", "activity onResume");
}

  • 布局
<lwj.com.scrollerdemo.MyView
    android:text="myView"
    android:layout_width="50dp"
    android:id="@+id/myview"
    android:layout_height="50dp"/>
  • MyView
public class MyView extends TextView {
    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        Log.e("zeal","MyView onMeasure");
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        Log.e("zeal", "MyView onLayout");
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Log.e("zeal", "MyView onDraw");
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        Log.e("zeal", "MyView onAttachedToWindow");
    }
}

  • MainActivity運行結(jié)果:
第一次獲取myView height:0;width:0
第三次獲取myView height:0;width:0
activity onResume
MyView onAttachedToWindow
MyView onMeasure
MyView onMeasure
MyView onLayout
第二次獲取myView height:150;width:150
MyView onDraw
MyView onMeasure
MyView onLayout
MyView onDraw

結(jié)合源碼分析結(jié)果出現(xiàn)的原因

  • 結(jié)果是在 post 前后獲取 view 寬高的值是為0,只有在 post 中獲取到的 view 的寬高才會有值。并且 View 是在 activity onResume 之后將 view attach 到 window 上的。int height = btnScrollBy.getHeight();int width = btnScrollBy.getWidth();之所以有正確的值是因為通過 post 這種方式,view已經(jīng)測量,布局完畢了,但是若是直接在onCreate獲取,view還沒有測量,布局完畢,所以獲取不到數(shù)據(jù)。

  • View.post(Runnable)源碼

public boolean post(Runnable action) {
    final AttachInfo attachInfo = mAttachInfo;
    if (attachInfo != null) {//在 activity onCreate 中attachInfo 當(dāng)前還沒有賦值
        return attachInfo.mHandler.post(action);
    }
    // Assume that post will succeed later
    ViewRootImpl.getRunQueue().post(action);
    return true;
}

根據(jù) mAttachInfo 是否為空調(diào)用不同的代碼,那么 mAttachInfo 是在哪里賦值的?縱觀 View 源碼,發(fā)現(xiàn) mAttachInfo 只有在一處地方賦值,那就是void dispatchAttachedToWindow(AttachInfo info, int visibility),該方法表示當(dāng) view 與 window 相關(guān)聯(lián)時回調(diào)。onCreate中調(diào)用時 mAttachInfo 還沒有賦值,所以代碼會執(zhí)行ViewRootImpl.getRunQueue().post(action)

  • 通過 ViewRootImpl.getRunQueue().post(action) 將 post 的任務(wù)添加 RunnQueue 隊列中。

因為 View 還沒 attach 到 window 中,也就是當(dāng)前 mAttachInfo 為 null, 為了讓 post 的任務(wù)能夠執(zhí)行,系統(tǒng)定義了 RunQueue 類做為隊列去管理這些任務(wù),隊列中的任務(wù)會在 ViewRootImpl#performTraversals() 方法中被執(zhí)行。也就是在 mAttachInfo 賦值之后通過 Handler 去執(zhí)行這些任務(wù)。

private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();

void postDelayed(Runnable action, long delayMillis) {
    HandlerAction handlerAction = new HandlerAction();
    handlerAction.action = action;
    handlerAction.delay = delayMillis;
    synchronized (mActions) {
        mActions.add(handlerAction);
    }
}

通過 post 最終會去調(diào)用 postDelayed 中是將 action 封裝成一個 HanlderAction 對象添加到 mActions 中去。在 RunQueue 源碼中的注釋中可以知道,我們將任務(wù)添加到任務(wù)隊列中 RunQueue 之后,會在 ViewRootImpl performTraversals 中執(zhí)行隊列中的任務(wù)。貼一下 Google 給的 RunQuee 源碼注釋:

/**
 * The run queue is used to enqueue pending work from Views when no Handler is
 * attached.  The work is executed during the next call to performTraversals on
 * the thread.
 * @hide
 */
static final class RunQueue {
    private final ArrayList<HandlerAction> mActions = new ArrayList<HandlerAction>();
    void post(Runnable action) {
        postDelayed(action, 0);
    }
    ...
}
  • 因為 RunQueue 中的任務(wù)是在 performTraversals 中執(zhí)行,所以代碼切換到 VeiwRootImpl.performTraversals 方法是怎么去執(zhí)行 RunQueue 的任務(wù)的?
private void performTraversals() {
    ...
    getRunQueue().executeActions(mAttachInfo.mHandler);
    ...
    performMeasure
    performLayout
    performDraw
    ...
}
public ViewRootImpl(Context context, Display display) {
    mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this);
}

在該方法中拿到 RunQueue 隊列,調(diào)用 executeActions 方法去執(zhí)行隊列中的任務(wù)。這里的 mAttachInfo 是在 ViewRootImpl 構(gòu)造中做了賦值操作了。

  • 在 RunQueue 中怎么通過 executeActions 去處理任務(wù)的?
void executeActions(Handler handler) {
    synchronized (mActions) {
        final ArrayList<HandlerAction> actions = mActions;
        final int count = actions.size();
        for (int i = 0; i < count; i++) {
            final HandlerAction handlerAction = actions.get(i);
            handler.postDelayed(handlerAction.action, handlerAction.delay);
        }
        actions.clear();
    }
}

遍歷隊列的所有任務(wù),然后交給 Handler 去執(zhí)行。到現(xiàn)在代碼基本是走通了,但是還是沒有解釋到為什么在 onCreate 中通過 post 方式就可以拿到 view 的寬高的原因。還記得上面說過的,通過 view.post 的方法將 一個 Runnable 任務(wù)添加到 RunQueue 中之后會在 performTraversals中調(diào)用執(zhí)行這個任務(wù),那么 performTraversals 中執(zhí)行 post 中的任務(wù)的代碼是 measure 和 layout 前面執(zhí)行的,那它是怎么保證拿到寬高值的?

final class TraversalRunnable implements Runnable {
        @Override
        public void run() {
            doTraversal();
        }
}
final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
void scheduleTraversals() {
    if (!mTraversalScheduled) {
        mTraversalScheduled = true;
        mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
        mChoreographer.postCallback(
                Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
        if (!mUnbufferedInputDispatch) {
            scheduleConsumeBatchedInput();
        }
        notifyRendererOfFramePending();
        pokeDrawLockIfNeeded();
    }
}

在 performTraversals() 中執(zhí)行 executeActions 是在測量之前調(diào)用的,但是卻可以在 post 中獲取到 view 的寬高值,這是為什么呢?在 scheduleTraversals() 方法中會執(zhí)行 mChoreographer.postCallback(.CALLBACK_TRAVERSAL, mTraversalRunnable, null); 也就是說將 mTraversalRunnable 作為一個任務(wù)添加到主線程的任務(wù)隊列中,因為 executeActions 內(nèi)部也是將任務(wù)一一的通過 Handler 添加到消息隊列中的,因此只有在 mTraversalRunnable 這個任務(wù)完畢之后 才會去執(zhí)行 post 中的任務(wù)。因此可以在 post 中獲取到 view 的寬高值。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容