A simple example of Android Scroller

Can someone give me a simple example about the Scroller class? As far as I understand, it encapsulates scrolling, so I need to start the calculation, and then manually update the ScrollView to new positions. So I just try

Scroller scroller = new Scroller(getApplicationContext()); scroller.startScroll(0, 0, 10, 10, 500); for (int i = 0; i < 100; i++) { Log.d("scroller", scroller.getCurrX()+" "+ scroller.getCurrY()); } 

All I have is just zeros. Where is my mistake?

+7
source share
2 answers
 private class Flinger implements Runnable { private final Scroller scroller; private int lastX = 0; Flinger() { scroller = new Scroller(getActivity()); } void start(int initialVelocity) { int initialX = scrollingView.getScrollX(); int maxX = Integer.MAX_VALUE; // or some appropriate max value in your code scroller.fling(initialX, 0, initialVelocity, 0, 0, maxX, 0, 10); Log.i(TAG, "starting fling at " + initialX + ", velocity is " + initialVelocity + ""); lastX = initialX; getView().post(this); } public void run() { if (scroller.isFinished()) { Log.i(TAG, "scroller is finished, done with fling"); return; } boolean more = scroller.computeScrollOffset(); int x = scroller.getCurrX(); int diff = lastX - x; if (diff != 0) { scrollingView.scrollBy(diff, 0); lastX = x; } if (more) { getView().post(this); } } boolean isFlinging() { return !scroller.isFinished(); } void forceFinished() { if (!scroller.isFinished()) { scroller.forceFinished(true); } } } 

Adapted from https://stackoverflow.com/a/312947/

+6
source

The final startScroll() parameter is the duration. Your for -loop probably ends before the scroller gets anything! :) And you should also call computeScrollOffset() Try this code, it works:

 Scroller scroller = new Scroller(getApplicationContext()); scroller.startScroll(0, 0, 100, 100, 500); while (!scroller.isFinished()) { Log.d("scroller", scroller.getCurrX() + " " + scroller.getCurrY()); scroller.computeScrollOffset(); } 
+4
source

All Articles