Skip to content

Instantly share code, notes, and snippets.

@khurram18
Created January 31, 2018 09:13
Show Gist options
  • Save khurram18/acbd576e778dc010047e8ac160d81375 to your computer and use it in GitHub Desktop.
Save khurram18/acbd576e778dc010047e8ac160d81375 to your computer and use it in GitHub Desktop.
Show counting in TextView Android with animation
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.TextView;
public class CountingHelper implements Runnable {
private final long mDuration;
private final int mStartingValue;
private final int mFinalValue;
private final TextView mTextView;
private final int mValueRange;
private long mProgressTime = 0;
private long mLastUpdateTime = 0;
private Interpolator mInterpolator = new AccelerateInterpolator();
public CountingHelper(int startingValue, int finalValue, int duration, TextView textView) {
mDuration = duration;
mStartingValue = startingValue;
mFinalValue = finalValue;
mTextView = textView;
mValueRange = mFinalValue - mStartingValue;
mLastUpdateTime = System.currentTimeMillis();
}
@Override
public void run() {
long now = System.currentTimeMillis();
mProgressTime += (now - mLastUpdateTime);
boolean shouldSchedule = true;
if (mProgressTime >= mDuration) {
mProgressTime = mDuration;
shouldSchedule = false;
}
mTextView.setText(String.valueOf(getCurrentValue()));
if (shouldSchedule) {
mTextView.postOnAnimation(this);
}
}
private int getCurrentValue() {
if (mProgressTime >= mDuration) {
return mFinalValue;
}
return (int) (mStartingValue + (mInterpolator.getInterpolation(
(float) mProgressTime / (float) mDuration) * mValueRange));
}
}
@khurram18
Copy link
Author

How to use?

// Activity or fragment
@Override
protected void onResume() {
    super.onResume();
    setValue(1500);
}
private void setValue(final int value) {
    TextView textView = // your text view
    textView.post(new Runnable() {
        @Override
        public void run() {
            textView.postOnAnimation(
                    new CountingHelper(0, // initial value
                            value, // final value
                            5000, // duration in milliseconds
                            textView));
        }
    });
}

@khurram18
Copy link
Author

Accompanying article can be found here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment