ScrollView中smoothScrollTo()方法无效

本文介绍了解决自定义View中smoothScrollTo()方法不起作用的问题,通过使用post()方法实现了平滑滚动效果,并探讨了其背后的实现原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在写一个自定义的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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值