Skip to content

Instantly share code, notes, and snippets.

@liu7yong
Last active December 21, 2015 12:19
Show Gist options
  • Save liu7yong/6304939 to your computer and use it in GitHub Desktop.
Save liu7yong/6304939 to your computer and use it in GitHub Desktop.
If you has your own custom View who has a RotateDrawable and want to make it rotate, following code may help. The trick is to call Drawable.setLevel() on the drawable.
private Drawable mLoadingDrawable;
private Transformation mTransformation;
private AlphaAnimation mAnimation;
private boolean mHasAnimation;
private Interpolator mInterpolator;
private long mLastDrawTime;
private static final int ANIMATION_RESOLUTION = 200;
private static final int MAX_LEVEL = 10000;
/**
* <p>
* Start the indeterminate progress animation.
* </p>
*/
void startAnimation() {
if (getVisibility() != VISIBLE) {
return;
}
mHasAnimation = true;
if (mInterpolator == null) {
mInterpolator = new LinearInterpolator();
}
if (mTransformation == null) {
mTransformation = new Transformation();
} else {
mTransformation.clear();
}
if (mAnimation == null) {
mAnimation = new AlphaAnimation(0.0f, 1.0f);
} else {
mAnimation.reset();
}
mAnimation.setRepeatMode(Animation.RESTART);
mAnimation.setRepeatCount(Animation.INFINITE);
mAnimation.setDuration(3500);
mAnimation.setInterpolator(mInterpolator);
mAnimation.setStartTime(Animation.START_ON_FIRST_FRAME);
postInvalidate();
}
/**
* <p>
* Stop the indeterminate progress animation.
* </p>
*/
void stopAnimation() {
mHasAnimation = false;
postInvalidate();
}
@Override
protected void onDraw(Canvas canvas) {
long time = getDrawingTime();
if (mHasAnimation) {
mAnimation.getTransformation(time, mTransformation);
float scale = mTransformation.getAlpha();
try {
mLoadingDrawable.setLevel((int) (scale * MAX_LEVEL));
} finally {
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
postInvalidateOnAnimation();
} else if (SystemClock.uptimeMillis() - mLastDrawTime >= ANIMATION_RESOLUTION) {
mLastDrawTime = SystemClock.uptimeMillis();
postInvalidateDelayed(ANIMATION_RESOLUTION);
}
}
super.onDraw(canvas);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment