ScrollView中smoothScrollTo()方法无效

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要在 ScrollView 实现横向排列的内容,你可以使用 CSS 的 Flexbox 布局来实现。下面是一个示例代码,演示了如何在 ScrollView 实现横向排列的内容: ```html <style> .scrollview-container { width: 300px; height: 200px; overflow-x: scroll; white-space: nowrap; } .scrollview-item { display: inline-block; width: 100px; height: 100px; background-color: gray; margin-right: 10px; } </style> <div class="scrollview-container"> <div class="scrollview-content"> <!-- 这里放置滚动内容 --> <!-- 可以是文本、图片或其他元素 --> <div class="scrollview-item"></div> <div class="scrollview-item"></div> <div class="scrollview-item"></div> <div class="scrollview-item"></div> <div class="scrollview-item"></div> <div class="scrollview-item"></div> </div> </div> ``` 在上述代码,我们使用了 `.scrollview-container` 类来定义 ScrollView 的容器样式。通过设置容器的宽度和高度,并将 `overflow-x` 属性设置为 `scroll` 来启用横向滚动。另外,我们使用 `white-space: nowrap;` 来防止内容换行。 然后,我们使用 `.scrollview-item` 类来定义横向排列的内容项的样式。通过设置 `display: inline-block;` 来使内容项水平排列,并设置适当的宽度、高度、背景颜色和右侧间距。 在 `.scrollview-content` 内部,你可以添加多个横向排列的内容项,通过复制 `<div>` 元素并为其添加 `.scrollview-item` 类。 这样,你就可以在 ScrollView 实现横向排列的内容了。根据需要,你可以根据样式类 `.scrollview-item` 来调整内容项的样式和尺寸。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值