Skip to content

Instantly share code, notes, and snippets.

@moradgholi
Last active April 7, 2016 16:43
Show Gist options
  • Save moradgholi/b75d390bf47829b1189b to your computer and use it in GitHub Desktop.
Save moradgholi/b75d390bf47829b1189b to your computer and use it in GitHub Desktop.
Animates an Integer in a Textview incrementally or decreamentaly using ObjectAnimator class.
import android.animation.ObjectAnimator;
import android.animation.TypeEvaluator;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Property;
import android.widget.TextView;
/**
* Created by Hossein Moradgholi (h.moradgholi[-AT-]icloud.com) on 1/14/15 AD.
*/
public class IntegerTextviewAnimator extends TextView {
private int DEFAULT_TIME_COHESION = 100;
public IntegerTextviewAnimator(Context context) {
super(context);
}
public IntegerTextviewAnimator(Context context, AttributeSet attrs) {
super(context, attrs);
}
public IntegerTextviewAnimator(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void animateValueTo(int value){
int currentValue = Integer.parseInt(getText().toString());
if (currentValue == value) return;
// Type evaluator for linear interpolation
TypeEvaluator<CharSequence> charSequenceTypeEvaluator = new TypeEvaluator<CharSequence>() {
@Override
public CharSequence evaluate(float fraction, CharSequence start, CharSequence end) {
int startValue = Integer.parseInt(start.toString());
int endValue = Integer.parseInt(end.toString());
int value = (int)((endValue - startValue) * fraction) + startValue;
return Integer.toString(value);
}
};
// we need to animate 'text' attribute
Property<TextviewAnimator, CharSequence> textViewStringProperty = Property.of(TextviewAnimator.class, CharSequence.class, "text");
CharSequence charSequence = Integer.toString(value);
final ObjectAnimator objectAnimator = ObjectAnimator.ofObject(this, textViewStringProperty, charSequenceTypeEvaluator, charSequence);
// animation duration
int animationDuration = Math.abs(currentValue - value) * DEFAULT_TIME_COHESION;
objectAnimator.setDuration(animationDuration);
objectAnimator.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment