ScrollView中smoothScrollTo()方法无效

来源:互联网 发布:阿里云邮箱 彻底删除 编辑:程序博客网 时间:2024/06/06 00:44

最近在写一个自定义的View继承于ScrollView时出现了一个问题,就是调用smoothScrollTo()方法时不起作用了,scrollTo()方法是没有问题的,但我们想要一种平滑的效果,所以就得使用smoothScrollTo()方法。网上找了好多方法,只有一种方法目前是有效的,就是使用post()方法,具体如下:


this.post(new Runnable() {      @Override      public void run() {          smoothScrollTo(0, 0);      }  }); 

this代表当前的类,也就是w继承于ScrollView的自定义View。

问题的现象是解决了,接下来就该看看其中的原理了。

跟进post()方法,可以看到这个是View类中的方法:


/**     * <p>Causes the Runnable to be added to the message queue.     * The runnable will be run on the user interface thread.</p>     *      * <p>This method can be invoked from outside of the UI thread     * only when this View is attached to a window.</p>     *     * @param action The Runnable that will be executed.     *     * @return Returns true if the Runnable was successfully placed in to the     *         message queue.  Returns false on failure, usually because the     *         looper processing the message queue is exiting.     */    public boolean post(Runnable action) {        Handler handler;        AttachInfo attachInfo = mAttachInfo;        if (attachInfo != null) {            handler = attachInfo.mHandler;        } else {            // Assume that post will succeed later            ViewRootImpl.getRunQueue().post(action);            return true;        }        return handler.post(action);    }

看到注释中的第二行,再看看代码中的Handler,有没有一种很熟悉的感觉呢----通过Handler发送消息到主线程中对界面进行更新。当然这只是看到这两行代码后的初步猜想,具体的原理在下面的链接中有解释,其中的涉及的Handler及其内部类和关联类的知识点需要深度学习:

http://www.cnblogs.com/akira90/archive/2013/03/06/2946740.html

原创粉丝点击