不可不知的开发技巧之View.Post()

稍微有点经验的安卓开发人员应该都知道View类的post和postDelayed方法。我们知道调用这个方法可以保证在UI线程中进行需要的操作,方便地进行异步通信。以下是官方文档对该方法的注释及源码。(postDelayed类似,不再赘述)

Causes the Runnable to be added to the message queue.The runnable will be run on the user interface thread.

public boolean post(Runnable action) {    
  final AttachInfo attachInfo = mAttachInfo;
  if (attachInfo != null) {       
  return attachInfo.mHandler.post(action);
  }    
// Assume that post will succeed later       
  ViewRootImpl.getRunQueue().post(action); 
  return true;
}

意思是将任务交由attachInfo中的Handler处理,保证在UI线程执行。从本质上说,它还是依赖于以Handler、Looper、MessageQueue、Message为基础的异步消息处理机制。相对于新建Handler进行处理更加便捷。因为attachInfo中的Handler其实是由该View的ViewRootImpl提供的,所以post方法相当于把这个事件添加到了UI 事件队列中。下面举一个常用的例子,比如在onCreate方法中获取某个view的宽高,而直接View#getWidth获取到的值是0。要知道View显示到界面上需要经历onMeasure、onLayout和onDraw三个过程,而View的宽高是在onLayout阶段才能最终确定的,而在Activity#onCreate中并不能保证View已经执行到了onLayout方法,也就是说Activity的声明周期与View的绘制流程并不是一一绑定。那为什么调用post方法就能起作用呢?首先MessageQueue是按顺序处理消息的,而在setContentView()后队列中会包含一条询问是否完成布局的消息,而我们的任务通过View#post方法被添加到队列尾部,保证了在layout结束以后才执行。

下面我举一个例子,加深大家的理解。假如你有一个需求,需要在某个页面中加入一个点击事件:从AppBar(ActionBar)下滑出一个控件,并且在该控件出现的同时依然可以点击AppBar上的MenuItem。因此不能使用popupWindow,只能将该控件放置于布局内,同时为了不阻碍其他控件的交互,需要将该view的可见性设置为GONE。于是你写下下面的代码

private void show(){
    if(myView.getVisibility()==View.GONE){
     myView.setVisibility(View.VISIBLE);
     }
    //对view执行动画
  }

但运行后却发现view是一瞬间显现的,并没有执行动画,我想你也猜到了,问题在于动画开始时该View还未成功被设置为可见,导致动画失效。
而把动画执行加入到View#post中后可以达到理想的效果

private void show(){
  if(myView.getVisibility()==View.GONE){
     myView.setVisibility(View.VISIBLE);
  }
     myView.post(new Runnable() {
            @Override
            public void run() {
                //对view执行动画
            }
        });
  }

原因在于将view的可见性从GONE设置为VISIBLE时会申请requestLayout,而layout是异步执行的,所以setVisibility方法返回了但是该操作还未完成。前面说了post方法可以保证新任务是在layout调用过后执行。下面是setVisibility方法中比较关键的代码:

if (newVisibility == VISIBLE) {
        if ((changed & VISIBILITY_MASK) != 0) {
            /*
             * If this view is becoming visible, invalidate it in case it changed while
             * it was not visible. Marking it drawn ensures that the invalidation will
             * go through.
             */
            mPrivateFlags |= PFLAG_DRAWN;
            invalidate(true);

            needGlobalAttributesUpdate(true);

            // a view becoming visible is worth notifying the parent
            // about in case nothing has focus.  even if this specific view
            // isn't focusable, it may contain something that is, so let
            // the root view try to give this focus if nothing else does.
            if ((mParent != null) && (mBottom > mTop) && (mRight > mLeft)) {
                mParent.focusableViewAvailable(this);
            }
        }
    }

    /* Check if the GONE bit has changed */
    if ((changed & GONE) != 0) {
        needGlobalAttributesUpdate(false);
        // 这里申请了重新布局
        requestLayout();

        if (((mViewFlags & VISIBILITY_MASK) == GONE)) {
            if (hasFocus()) clearFocus();
            clearAccessibilityFocus();
            destroyDrawingCache();
            if (mParent instanceof View) {
                // GONE views noop invalidation, so invalidate the parent
                ((View) mParent).invalidate(true);
            }
            // Mark the view drawn to ensure that it gets invalidated properly the next
            // time it is visible and gets invalidated
            mPrivateFlags |= PFLAG_DRAWN;
        }
        if (mAttachInfo != null) {
            mAttachInfo.mViewVisibilityChanged = true;
        }
    }

总结

调用View.post()既方便又可以保证指定的任务在视图操作中顺序执行。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,297评论 25 709
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 11,721评论 0 17
  • 当秋风吹来 我已看到冬的寒冷 它正在前方等待 苍老硕大的梧桐 挡住了秋雨的袭来 却从脚底传来阵阵的冰凉 前方多彩的...
    墨子岩阅读 3,318评论 0 0
  • 元宵节,吃过晚饭和爸妈还有街坊邻居们结伴去几十公里外的村落看烟火大会。 即使烟火大会没有满天不间断的烟花,但广场张...
    TA她説阅读 3,630评论 1 1
  • 每个人的青春或许都有一段言不由己吧 但那又怎样 就这样告诉自己 不要委屈自己 有什么不痛快 找个合适的时机和由头说...
    王老二也阅读 1,534评论 0 1