View.post获取控件宽高原理探索

首先写这篇文章之前贴上二篇分析较好的博客,非常感谢博主的奉献精神
http://blog.csdn.net/scnuxisan225/article/details/49815269
http://mp.weixin.qq.com/s/laR3_Xvr0Slb4oR8D1eQyQ

大家都遇到过在android开发时,在Activity中的onCreate方法中通过控件的getMeasureHeight/getHeight或者getMeasureWidth/getWidth方法获取到的宽高大小都是0,我相信大家遇到这种问题时首先会想到打开度娘然后一搜,常见的二种解决方案就出来了。

1.通过监听Draw/Layout事件:ViewTreeObserver

 1 view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
 2         @Override
 3         public void onGlobalLayout() {
 4             mScrollView.post(new Runnable() {
 5                 public void run() {
 6                     view.getHeight(); //height is ready
 7                 }
 8             });
 9         }
10 });

当我们注册这个监听时,控件经过 onMeasure->onLayout->onDraw一系列方法渲染完成后会去回调这个注册的监听,我们自然能拿到控件的宽高。

2.第二种方法我比较喜欢,只要用View.post()一个runnable就可以了

1 ...
2       view.post(new Runnable() {
3             @Override
4             public void run() {
5                 view.getHeight(); //height is ready
6             }
7         });
8 ...

我们一般这么用总能拿到控件的宽高大小,方法是非常好用,但是本着十万个为什么态度,我决定把这个方法的原理整理一遍。

我们先回忆下,android中每个界面是个Activity,每个Activity最顶层是一个DecorView,它包裹我们自定义的布局.
好接下来我们看下View的post方法干了什么

    public boolean post(Runnable action) {
        final AttachInfo attachInfo = mAttachInfo;
        if (attachInfo != null) {
            return attachInfo.mHandler.post(action);
        }

        // Postpone the runnable until we know on which thread it needs to run.
        // Assume that the runnable will be successfully placed after attach.
        getRunQueue().post(action);
        return true;
    }

这里面判断mAttachInfo是不是为空,如果不为null时,直接取出mAttachInfo中存放的Handler对象去post 我们的Runnable任务,如果为null的话我们看看getRunQueue()方法会做什么

    private HandlerActionQueue getRunQueue() {
        if (mRunQueue == null) {
            mRunQueue = new HandlerActionQueue();
        }
        return mRunQueue;
    }

它会去创建一次HandlerActionQueue对象然后把这个对象返回,好我们点进这个对象看一下

public class HandlerActionQueue {
    private HandlerAction[] mActions;
    private int mCount;

    public void post(Runnable action) {
        postDelayed(action, 0);
    }

    public void postDelayed(Runnable action, long delayMillis) {
        final HandlerAction handlerAction = new HandlerAction(action, delayMillis);

        synchronized (this) {
            if (mActions == null) {
                mActions = new HandlerAction[4];
            }
            mActions = GrowingArrayUtils.append(mActions, mCount, handlerAction);
            mCount++;
        }
    }
....

我们之前代码可以看到如果mAttachInfo为null的话会去调用HandlerActionQueue对象中的post方法传递我们Runnable任务,接着会调用postDelayed方法,这个方法会把我们的Runnable任务和需要延迟的时间都封装到HandlerAction对象中然后加入到下面的HandlerAction[]数组中,点进去也会发现HandlerAction 就是一个简单的封装类。

 private static class HandlerAction {
        final Runnable action;
        final long delay;

        public HandlerAction(Runnable action, long delay) {
            this.action = action;
            this.delay = delay;
        }

        public boolean matches(Runnable otherAction) {
            return otherAction == null && action == null
                    || action != null && action.equals(otherAction);
        }
    }

现在我们回过头思考一下就会有疑惑了,情景回到post方法中,我们根据mAttachInfo这个值判断是直接post发送任务还是把任务放入队列,那么这个值是什么时候被赋值的呢?

答案就在ViewRootImpl类中,在ViewRootImpl构造中有这么端代码创建了AttachInfo对象。

 mAttachInfo = new View.AttachInfo(mWindowSession, mWindow, display, this, mHandler, this);

然后在performTraversals()方法中会去调用这么段代码 ,这段代码执行在大家很熟悉的 performMeasure、performLayout、performDraw方法之前。

host.dispatchAttachedToWindow(mAttachInfo, 0);

host就是DecorView,它是一个ViewGroup,所以我们先看看ViewGroup中的dispatchAttachedToWindow方法

    @Override
    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
        mGroupFlags |= FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW;
        super.dispatchAttachedToWindow(info, visibility);
        mGroupFlags &= ~FLAG_PREVENT_DISPATCH_ATTACHED_TO_WINDOW;

        final int count = mChildrenCount;
        final View[] children = mChildren;
        for (int i = 0; i < count; i++) {
            final View child = children[i];
            child.dispatchAttachedToWindow(info,
                    combineVisibility(visibility, child.getVisibility()));
        }
        final int transientCount = mTransientIndices == null ? 0 : mTransientIndices.size();
        for (int i = 0; i < transientCount; ++i) {
            View view = mTransientViews.get(i);
            view.dispatchAttachedToWindow(info,
                    combineVisibility(visibility, view.getVisibility()));
        }
    }

可以看到主要这个方法中会调用自己和所有child父类也就是View中的dispatchAttachedToWindow方法,那我们看看View中的dispatchAttachedToWindow方法究竟干了些什么事情吧?

  /**
     * @param info the {@link android.view.View.AttachInfo} to associated with
     *        this view
     */
    void dispatchAttachedToWindow(AttachInfo info, int visibility) {
        mAttachInfo = info;
        if (mOverlay != null) {
            mOverlay.getOverlayView().dispatchAttachedToWindow(info, visibility);
        }
        mWindowAttachCount++;
        // We will need to evaluate the drawable state at least once.
        mPrivateFlags |= PFLAG_DRAWABLE_STATE_DIRTY;
        if (mFloatingTreeObserver != null) {
            info.mTreeObserver.merge(mFloatingTreeObserver);
            mFloatingTreeObserver = null;
        }

        registerPendingFrameMetricsObservers();

        if ((mPrivateFlags&PFLAG_SCROLL_CONTAINER) != 0) {
            mAttachInfo.mScrollContainers.add(this);
            mPrivateFlags |= PFLAG_SCROLL_CONTAINER_ADDED;
        }
        // Transfer all pending runnables.
        if (mRunQueue != null) {
            mRunQueue.executeActions(info.mHandler);
            mRunQueue = null;
        }
        performCollectViewAttributes(mAttachInfo, visibility);
        onAttachedToWindow();

        ListenerInfo li = mListenerInfo;
        final CopyOnWriteArrayList<OnAttachStateChangeListener> listeners =
                li != null ? li.mOnAttachStateChangeListeners : null;
        if (listeners != null && listeners.size() > 0) {
            // NOTE: because of the use of CopyOnWriteArrayList, we *must* use an iterator to
            // perform the dispatching. The iterator is a safe guard against listeners that
            // could mutate the list by calling the various add/remove methods. This prevents
            // the array from being modified while we iterate it.
            for (OnAttachStateChangeListener listener : listeners) {
                listener.onViewAttachedToWindow(this);
            }
        }

        int vis = info.mWindowVisibility;
        if (vis != GONE) {
            onWindowVisibilityChanged(vis);
            if (isShown()) {
                // Calling onVisibilityChanged directly here since the subtree will also
                // receive dispatchAttachedToWindow and this same call
                onVisibilityAggregated(vis == VISIBLE);
            }
        }

        // Send onVisibilityChanged directly instead of dispatchVisibilityChanged.
        // As all views in the subtree will already receive dispatchAttachedToWindow
        // traversing the subtree again here is not desired.
        onVisibilityChanged(this, visibility);

        if ((mPrivateFlags&PFLAG_DRAWABLE_STATE_DIRTY) != 0) {
            // If nobody has evaluated the drawable state yet, then do it now.
            refreshDrawableState();
        }
        needGlobalAttributesUpdate(false);
    }

这段代码比较长但是我们一眼就可以看到mAttachInfo 正是在这里被赋值的,而被赋值调用的地方正是在上面ViewRootImpl中的performTraversals()方法中!
然后我们接着看这个方法

 mRunQueue.executeActions(info.mHandler);

调用了这句代码,执行了我们前面提到的HandlerAction类中的executeActions方法,我们看下这个方法做了些什么事情

    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;
        }
    }

ok,一切思路都那么清晰了,这个方法会用我们传递进来的mAttachInfo中的Handler去遍历我们View.post储存的所有Runnable任务。

至此貌似所有的流程都分析完毕了,但是如果有细心的同学会发现前面的分析有漏洞,哪里呢?就是在执行ViewRootImpl中的performTraversals()方法的时候,

host.dispatchAttachedToWindow(mAttachInfo, 0);

调用这个方法明明执行在测量,布局,绘制三个方法之前,也就是说调用这个方法后就会拿到我们传递mAttachInfo中Handler去执行View.post中的Runnable,然后才会去调用测量,布局,绘制三个方法,那理论上还是拿不到宽高值啊,这个时候还没执行测量啊,可是为什么结果可以拿到呢???

没关系,我一开始也是这么认为的并且陷入了很长一段时间的困惑当中,这是由于不了解android消息机制导致的,Android的运行其实是一个消息驱动模式,也就是说在Android主线程中默认是创建了一个Handler的,并且这个主线程中创建了一个Looper去循环遍历执行队列中的Message,这个执行是同步的,也就是说执行完一个Message后才会去继续执行下一个,调用performTraversals()这个方法是通过主线程的Looper遍历执行的,这个方法还没执行结束,然后我们在这个方法中通过mAttachInfo中Handler去执行View.post中的Runnable,mAttachInfo中Handler也是创建在主线程,所以它会在上一个消息执行结束后才会被执行,也就是说会在测量,布局,绘制执行后才执行,这样自然而然能拿到控件的宽和高啦。

我不禁敬佩,Android团队的这个机制设计的太巧妙了。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值