Skip to content

Instantly share code, notes, and snippets.

@natebass
Created December 11, 2014 00:17
Show Gist options
  • Save natebass/437e8237f543a259cf02 to your computer and use it in GitHub Desktop.
Save natebass/437e8237f543a259cf02 to your computer and use it in GitHub Desktop.
Bounce animation with ValueAnimator
package com.natebass.bouncingballs;
import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.View;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new AnimationView(this));
}
static class AnimationView extends View {
Bitmap bitmap;
Paint paint = new Paint();
int shapeX, shapeY, shapeW, shapeH;
AnimationView(Context context) {
super(context);
setupShape();
}
AnimationView(Context context, AttributeSet attrs) {
super(context, attrs);
setupShape();
}
AnimationView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setupShape();
}
private void setupShape() {
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.search);
shapeW = bitmap.getWidth();
shapeH = bitmap.getHeight();
setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startAnimation();
}
});
}
public void setShapeX(int pShapeX) {
int minX = shapeX;
int maxX = shapeX + shapeW;
shapeX = pShapeX;
minX = Math.min(shapeX, minX);
maxX = Math.max(shapeX + shapeW, maxX);
invalidate(minX, shapeY, maxX, shapeY + shapeH);
}
public void setShapeY(int pShapeY) {
int minY = shapeY;
int maxY = shapeY + shapeW;
shapeY = pShapeY;
minY = Math.min(shapeY, minY);
maxY = Math.max(shapeY + shapeH, maxY);
invalidate(shapeX, minY, shapeX + shapeW, maxY);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
shapeX = (w - bitmap.getWidth()) / 2;
shapeY = 0;
}
@Override
protected void onDraw(Canvas pCanvas) {
pCanvas.drawBitmap(bitmap, shapeX, shapeY, paint);
}
void startAnimation() {
ValueAnimator valueAnimator = getValueAnimator();
valueAnimator.start();
}
private ValueAnimator getValueAnimator() {
ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
setShapeY((int) (animation.getAnimatedFraction() * (getHeight() - shapeH)));
}
});
return valueAnimator;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment