Android Scroller tutorial with examples (2024)

Table of Contents
Introduction Example Related

PreviousNext

This class encapsulates scrolling.

Introduction

This class encapsulates scrolling.

You can use scrollers (Scroller or OverScroller) to collect the data you need to produce a scrolling animation—for example, in response to a fling gesture.

Scrollers track scroll offsets for you over time, but they don't automatically apply those positions to your view.

It's your responsibility to get and apply new coordinates at a rate that will make the scrolling animation look smooth.

Here is a simple example:

private Scroller mScroller = new Scroller(context); ... public void zoomIn() { // Revert any animation currently in progress  mScroller.forceFinished(true); // Start scrolling by providing a starting point and  // the distance to travel mScroller.startScroll(0, 0, 100, 0);  // Invalidate to request a redraw  invalidate(); } 

To track the changing positions of the x/y coordinates, use #computeScrollOffset.

The method returns a boolean to indicate whether the scroller is finished.

If it isn't, it means that a fling or programmatic pan operation is still in progress.

You can use this method to find the current offsets of the x and y coordinates, for example:

if (mScroller.computeScrollOffset()) { // Get current x and y positions  int currX = mScroller.getCurrX(); int currY = mScroller.getCurrY(); ...}

Example

The following code shows how to use Scroller from android.widget.

Example 1

import android.app.Activity;import android.content.Context;import android.util.AttributeSet;import android.view.MotionEvent;import android.view.View;import android.view.ViewConfiguration;import android.view.animation.DecelerateInterpolator;import android.widget.Scroller;public class SwipeBackView extends View { public interface SwipeBackListener { void onSwipeBack(); }//    ww  w   .   de    m  o 2  s .  c   o m   private SwipeBackListener swipeBackListener; public void setSwipeBackListener(SwipeBackListener swipeBackListener) { this.swipeBackListener = swipeBackListener; } /////////////////////////////////////////// private View rootView; private int touchSlop; private Scroller scroller; private boolean startScroll = false; private float lastX; public SwipeBackView(Context context) { super(context); init(context); } public SwipeBackView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } private void init(Context context) { final Activity activity = (Activity) context; rootView = activity.getWindow().getDecorView(); touchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); scroller = new Scroller(context, new DecelerateInterpolator()); swipeBackListener = new SwipeBackListener() { @Override public void onSwipeBack() { activity.finish(); activity.overridePendingTransition(R.anim.nothing, R.anim.out_slide_to_right); } }; } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: lastX = event.getRawX(); return true; case MotionEvent.ACTION_MOVE: float curX = event.getRawX(); int delta = (int) (curX - lastX); if (delta > touchSlop && !startScroll) { startScroll = true; } if (startScroll && rootView.getScrollX() - delta <= 0) { rootView.scrollBy(-delta, 0); lastX = curX; } break; case MotionEvent.ACTION_UP: startScroll = false; if (-rootView.getScrollX() > rootView.getWidth() / 3) { if (swipeBackListener != null) { swipeBackListener.onSwipeBack(); } } else { scroller.startScroll(rootView.getScrollX(), 0, -rootView.getScrollX(), 0); invalidate(); } break; default: break; } return super.onTouchEvent(event); } @Override public void computeScroll() { if (scroller.computeScrollOffset()) { rootView.scrollTo(scroller.getCurrX(), scroller.getCurrY()); invalidate(); } }}

Example 2

import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapShader;import android.graphics.Canvas;import android.graphics.Matrix;import android.graphics.Shader;import android.graphics.drawable.Drawable;import android.util.AttributeSet;import android.view.animation.LinearInterpolator;import android.widget.Scroller;import android.widget.TextView;public class TitanicTextViewEx extends TextView { private Scroller mScroller; private Drawable wave; private BitmapShader mShader; // shader matrix private Matrix shaderMatrix; private int width; private int height; boolean up = false; private boolean running = false; public TitanicTextViewEx(Context context) { super(context); init();//   w w   w .  d  e   m   o2  s   .  c   o m  } public TitanicTextViewEx(Context context, AttributeSet attrs) { super(context, attrs); init(); } public TitanicTextViewEx(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { mScroller = new Scroller(this.getContext(), new LinearInterpolator()); shaderMatrix = new Matrix(); } public void start() { running = true; invalidate(); } @Override public void computeScroll() { if (running) { if (mScroller.computeScrollOffset()) { shaderMatrix.setTranslate(mScroller.getCurrX(), mScroller.getCurrY()); invalidate(); } else { if (height != 0) { if (up) { mScroller.startScroll(0, -height / 2, 10 * width, height, 10000); up = false; } else { mScroller.startScroll(0, height / 2, 10 * width, -height, 10000); up = true; } } else { shaderMatrix.setTranslate(0, height / 2); } invalidate(); } } } private void createShalder() { if (wave == null) { wave = getResources().getDrawable(R.drawable.wave); } width = wave.getIntrinsicWidth(); height = this.getHeight(); Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); wave.setBounds(0, 0, width, height); Canvas c = new Canvas(b); c.drawColor(getCurrentTextColor()); wave.draw(c); mShader = new BitmapShader(b, Shader.TileMode.REPEAT, Shader.TileMode.CLAMP); shaderMatrix.setTranslate(0, height / 2); } @Override public void draw(Canvas canvas) { if (running) { if (mShader == null) { createShalder(); } mShader.setLocalMatrix(shaderMatrix); this.getPaint().setShader(mShader); } super.draw(canvas); }}

Example 3

import android.content.Context;import android.content.res.TypedArray;import android.graphics.Canvas;import android.graphics.Paint;import android.graphics.drawable.Drawable;import android.util.AttributeSet;import android.view.View;import android.view.animation.Interpolator;import android.widget.Scroller;/**/*  w w   w .  d   e m   o2  s  .  c  o    m*/ * TODO: document your custom view class. */public class TabSliderView extends View { private int color; private float lineHeight; private Paint paint; private int position = 0; private Scroller scroller; private int tabCount = 0; int contentWidth = 0; int prevNotifyPosition = -1; public interface OnMoveEndListener { void onMoveEnd(int position); } private OnMoveEndListener listener; public void setOnMoveEnd(OnMoveEndListener l) { listener = l; } public void setTabCount(int tabCount) { this.tabCount = tabCount; } public void setPosition(final int position) { if (this.position != position) { this.position = position; int dx = contentWidth * position / tabCount - scroller.getCurrX(); scroller.startScroll(scroller.getCurrX(), 0, dx, 0, 400); invalidate(); } } private Drawable indicator; public TabSliderView(Context context) { super(context); init(null, 0); } public TabSliderView(Context context, AttributeSet attrs) { super(context, attrs); init(attrs, 0); } public TabSliderView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(attrs, defStyle); } private void init(AttributeSet attrs, int defStyle) { // Load attributes final TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.TabSliderView, defStyle, 0); if (a.hasValue(R.styleable.TabSliderView_indicator)) { indicator = a.getDrawable(R.styleable.TabSliderView_indicator); indicator.setCallback(this); color = a.getColor(R.styleable.TabSliderView_barColor, 0x0); lineHeight = a.getDimension(R.styleable.TabSliderView_lineHeight, 0); } a.recycle(); paint = new Paint(); paint.setColor(color); scroller = new Scroller(getContext(), new Interpolator() { private float s = 1.70158f; public float getInterpolation(float t) { return calculate(t, 0, 1, 1); } public Float calculate(float t, float b, float c, float d) { return c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b; } }); } public void setInterpolator(Interpolator interpolator) { scroller = new Scroller(getContext(), interpolator); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (tabCount == 0) { return; } int paddingLeft = getPaddingLeft(); int paddingTop = getPaddingTop(); int paddingRight = getPaddingRight(); int paddingBottom = getPaddingBottom(); contentWidth = getWidth() - paddingLeft - paddingRight; int contentHeight = getHeight() - paddingTop - paddingBottom; if (indicator != null) { int bgWidth = contentWidth / tabCount; indicator.setBounds(scroller.getCurrX() + paddingLeft - bgWidth / 10, paddingTop, scroller.getCurrX() + paddingLeft + bgWidth + bgWidth / 10, paddingTop + contentHeight - (int) lineHeight); indicator.draw(canvas); } canvas.drawRect(paddingLeft, paddingTop + contentHeight - lineHeight, paddingLeft + contentWidth, paddingTop + contentHeight, paint); if (scroller.computeScrollOffset()) { invalidate(); } else { if (prevNotifyPosition != position) { if (listener != null) { prevNotifyPosition = position; listener.onMoveEnd(position); } } } }}

PreviousNext

Related

  • Android Scroller isFinished()
  • Android Scroller Scroller(Context context)
  • Android Scroller Scroller(Context context, Interpolator interpolator)
  • Android Scroller tutorial with examples
  • Android android.widget ScrollView
  • Android ScrollView addOnLayoutChangeListener(OnLayoutChangeListener listener)
  • Android ScrollView addView(View child)
Android Scroller tutorial with examples (2024)
Top Articles
Latest Posts
Article information

Author: Gregorio Kreiger

Last Updated:

Views: 5752

Rating: 4.7 / 5 (57 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Gregorio Kreiger

Birthday: 1994-12-18

Address: 89212 Tracey Ramp, Sunside, MT 08453-0951

Phone: +9014805370218

Job: Customer Designer

Hobby: Mountain biking, Orienteering, Hiking, Sewing, Backpacking, Mushroom hunting, Backpacking

Introduction: My name is Gregorio Kreiger, I am a tender, brainy, enthusiastic, combative, agreeable, gentle, gentle person who loves writing and wants to share my knowledge and understanding with you.