停止滚动用户触摸时查看滚动



我会自动将滚动视图滚动到视图的底部。

scrollView.smoothScrollTo(0, scrollView.getBottom());

如果用户触摸布局,我需要滚动停止&停留在当前位置。

scrollView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                //// TODO: 01/08/16 STOP SCROLLING
            }
            return false;
        }
    });

我试过smoothScrollBy(0,0);,但它不起作用。

我用ObjectAnimator解决了这个问题。它不仅能很好地解决问题,而且还能让我控制滚动速度。

我更换了

scrollView.smoothScrollTo(0, scrollView.getBottom());

带有

objectAnimator = ObjectAnimator
                .ofInt(scrollView, "scrollY", scrollView.getBottom())
                .setDuration(3000);
objectAnimator.start();

然后

scrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    objectAnimator.cancel();
                }
                return false;
            }
        });

一种方法可能是使用smoothScrollToPosition,它可以停止任何现有的滚动动作。注意,此方法需要API级别>=8(Android 2.2,Froyo)。

请注意,如果当前位置远离所需位置,那么平滑滚动将需要相当长的时间,并且看起来有点不稳定(至少在我在Android 4.4 KitKat上的测试中是这样)。我还发现,调用setSelection和smoothScrollToPosition的组合有时会导致位置稍微"错过",这似乎只有在当前位置非常接近所需位置时才会发生。

在我的例子中,当用户按下按钮时,我希望我的列表跳到顶部(位置=0)(这与您的用例略有不同,因此您需要根据自己的需求进行调整)。

我使用以下方法进行

private void smartScrollToPosition(ListView listView, int desiredPosition) {
    // If we are far away from the desired position, jump closer and then smooth scroll
    // Note: we implement this ourselves because smoothScrollToPositionFromTop
    // requires API 11, and it is slow and janky if the scroll distance is large,
    // and smoothScrollToPosition takes too long if the scroll distance is large.
    // Jumping close and scrolling the remaining distance gives a good compromise.
    int currentPosition = listView.getFirstVisiblePosition();
    int maxScrollDistance = 10;
    if (currentPosition - desiredPosition >= maxScrollDistance) {
        listView.setSelection(desiredPosition + maxScrollDistance);
    } else if (desiredPosition - currentPosition >= maxScrollDistance) {
        listView.setSelection(desiredPosition - maxScrollDistance);
    }
    listView.smoothScrollToPosition(desiredPosition); // requires API 8
}

在我的按钮操作处理程序中,我如下调用

case R.id.action_go_to_today:
    ListView listView = (ListView) findViewById(R.id.lessonsListView);
    smartScrollToPosition(listView, 0); // scroll to top
    return true;

上面的内容并不能直接回答你的问题,但如果你能检测到当前位置何时处于或接近你想要的位置,那么也许你可以使用smoothScrollToPosition来停止滚动。

最新更新