Can I reuse ValueAnimator? - android

I have the following code (Android project in Scala):
val animator = new ValueAnimator
animator.setFloatValues(0f, 100f)
animator.setDuration(20000L)
animator.addUpdateListener(this) // prints current value to console
animator.start
override def onTouch(v: View, event: MotionEvent) = {
animator.setFloatValues(100f, 0f)
animator.setCurrentPlayTime(0)
if (!animator.isRunning) animator.start
true
}
If I touch the screen while animator is running then it correctly starts working backwards (since I've swapped the values). But if I touch the screen after it is finished then nothing happens, it does not start over.
Question is can I reuse this animator somehow and make it work again for given values after it has been stopped?

You can reuse animator in the following way:
...
animator.end();
animator.setFloatValues(...);
animator.start();
...
You can also use animator.cancel() instead of animator.end() and pass the last value from the last animation to the new animation as a starting float. For instance, if the last animated value is 50, you can call animator.setFloatValues(50, 0f) so your animations will look connected.
Considering the accepted answer states it's impossible, I would like to mention that the described approach is used in Touch Circle app when users make tap with two fingers. BTW, it's a very nice effect when object trembles a little bit - use it as you wish, code exerpt is below:
void shapeTremble(long delay) {
if (null == animatorTremble) {
ValueAnimator animator = new ValueAnimator();
animator.setDuration(850).setInterpolator(new AccelerateDecelerateInterpolator());
animator.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
setCircleScale((Float) valueAnimator.getAnimatedValue(), true);
}
});
animatorTremble = animator;
} else {
animatorTremble.cancel();
}
animatorTremble.setFloatValues(circleScale, 0.85f, 1.05f, 0.95f, 1.025f, 1.0f);
animatorTremble.setStartDelay(delay);
animatorTremble.start();
}

You cannot reuse an animation.
You need to reset() and reinitialize an animation object by calling the initialize() method before using the same object again. This is similar to instantiating a new animation object.

Related

How to start multiple ObjectAnimator on view simultaneously?

Here i am trying to move a view on a path with ObjectAnimator and also need to set one more scale animation on same view.
ObjectAnimator objectAnimator = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP)
{
objectAnimator = ObjectAnimator.ofFloat(view, View.X, View.Y, path);
}
if (objectAnimator != null) {
objectAnimator.setDuration(2500);
objectAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
objectAnimator.start();
view.startAnimation(scaleRection);// this is not working because changing of x y position
need to start another Animation when objectAnimator.start();
also tried with listener
objectAnimator.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
view.startAnimation(scaleRection);
}
#Override
public void onAnimationEnd(Animator animation)
{
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
You can also use an AnimatorSet play together https://developer.android.com/reference/android/animation/AnimatorSet.html#playTogether and it's builder function https://developer.android.com/reference/android/animation/AnimatorSet.Builder
To play Two ObjectAnimator together
e.g.
AnimatorSet animationSet = new AnimatorSet();
ObjectAnimator scaleY = ObjectAnimator.ofFloat(view,"scaleY", 1f, 0f);
scaleY.setDuration(5000);
scaleY.setInterpolator(new AccelerateDecelerateInterpolator());
ObjectAnimator scaleX = ObjectAnimator.ofFloat(view,"scaleX", 1f, 0f);
scaleX.setDuration(5000);
scaleX.setInterpolator(new AccelerateDecelerateInterpolator());
animationSet.playTogether(scaleX, scaleY);
animationSet.start();
I would suggest using ViewPropertyAnimator.
From the docs :
This class enables automatic and optimized animation of select
properties on View objects. If only one or two properties on a View
object are being animated, then using an ObjectAnimator is fine; the
property setters called by ObjectAnimator are well equipped to do the
right thing to set the property and invalidate the view appropriately.
But if several properties are animated simultaneously, or if you just
want a more convenient syntax to animate a specific property, then
ViewPropertyAnimator might be more well-suited to the task.
This class may provide better performance for several simultaneous
animations, because it will optimize invalidate calls to take place
only once for several properties instead of each animated property
independently causing its own invalidation. Also, the syntax of using
this class could be easier to use because the caller need only tell
the View object which property to animate, and the value to animate
either to or by, and this class handles the details of configuring the
underlying Animator class and starting it.
You can chain as many animations as you like at once in one line of code :
view.animate().translationX(...).translationY(...).scaleX(...).scaleY(...).setInterpolator(new AccelerateDecelerateInterpolator()).setDuration(2500);
if you need different values for your duration or similar, you can do it with two lines :
view.animate().translationX().setDuration(...) ...
view.animate().scaleX().setDuration(...) ...
There are also methods translationXBy() and scaleXBy() which might be more suitable for your case, and you can also set a listener etc. Check the docs for all available methods

Any tips for reducing lag when running multiple animations at the same time?

Once my app reaches ~4+ animations running concurrently, the animations start to lag a little. Are there any ways I could fix/optimize that? I am using ObjectAnimator and ValueAnimator.
So, if the views are not having to redraw themselves during the animations, you can enable hardware layers during the duration of the animations. For instance:
final View myView = // your view
Animator animator = ObjectAnimator.ofFloat(myView, View.ALPHA, 0f, 1f);
animator.setDuration(1000);
animator.addAnimatorListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animator) {
myView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
#Override
public void onAnimationCancel(Animator animator) {
myView.setLayerType(View.LAYER_TYPE_NONE, null);
}
#Override
public void onAnimationEnd(Animator animator) {
// See http://stackoverflow.com/a/19615205/321697
myView.post(new Runnable() {
#Override
public void run() {
myView.setLayerType(View.LAYER_TYPE_NONE, null);
}
}
}
}
animator.start();
I'd suggest breaking that listener implementation out into a separate class, but the general idea is that you want to put the view into a hardware backed layer as soon as the animation starts (animation properties such as translation, rotation, scale, and alpha are incredibly cheap when backed by a hardware layer) and then clear the layer once the animation is complete.
In the onAnimationEnd callback, you'll notice a link to another answer where there's a bug with 4.0.x if you set the layer type to none in the onAnimationEnd callback. If you're only supporting 4.1 and above, the runnable indirection shouldn't be necessary.
EDIT: If you're animating a color transition, you probably don't want to do the above, as changing the color of the view will require it to be redrawn, causing it to rebuild the hardware layer on each frame.
If you have not used ViewPropertyAnimator, you better do. I moved and flipped(changed picture) 52 imageViews (one deck of playing cards) smoothly.
Here's an example on how to use ViewPropertyAnimator.

How to execute TranslateAnimation sequentially without knowing how many translate you'll have to do (android)?

The question is simple but i tried to search a solution in other similar questions, and i couldn't.
I have a arraylist path containing objects of type Coordinata that is an object containing two float X and Y, that is a coordinate. In substance, it's a list of coordinate. I need my ImageView image to move on a map on my view doing several subsequential TranslateTrasformation between the coordinate contained in the list path.
This can be easily done in the case of a fixed number of translation, doing the first translate and attaching it a setAnimationListener which could catch the end of the first animation and start in that moment the second and so on. I tried to iterate the process on my list path, using a while cycle, for i cannot really know how many coordinate will be in the path when the animation will start.
The result is the animation go on for the first couple of coordinates and then jump executing the animation for the last two coordinate in the path, ignoring all that is among these.
What is going on? I'm messing up with objects?
List<Coordinata> path; // properly filled with coordinates
Coordinata coordTempStart;
Coordinata coordTempArrival;
ImageView image;
ListIterator<Coordinata> pathIterator = path.listIterator();
if(pathIterator.hasNext()){
coordTempStart = (Coordinata) pathIterator.next();
}
if(pathIterator.hasNext()){
coordTempArrival = (Coordinata) pathIterator.next();
animation = new TranslateAnimation(coordTempStart.getX(),
coordTempArrival.getX(),
coordTempStart.getY(),
coordTempArrival.getY());
animation.setDuration(3000);
image.startAnimation(animation);
}
while(pathIterator.hasNext()){
coordTempStart=coordTempArrival;
coordTempArrival = (Coordinata) pathIterator.next();
animation.setAnimationListener(new TranslateAnimation.AnimationListener(){
public void onAnimationStart(Animation arg0) {}
public void onAnimationRepeat(Animation arg0) {}
public void onAnimationEnd(Animation arg0) {
animation = new TranslateAnimation(coordTempStart.getX(),
coordTempArrival.getX(),
coordTempStart.getY(),
coordTempArrival.getY());
animation.setDuration(3000);
image.startAnimation(animation);
}
});
}
I suggest to use ObjectAnimator and AnimatorSet to animate views. Object animator is available only for api > 11 but you can use NineOldAndroid if you have to keep the compatibility.
your code will be something like this (in pseudocode):
...
AnimatorSet animatorSet = new AnimatorSet();
while(pathIterator.hasNext()){
...
//Set _your_delta_x_ and _your_delta_y_ from iterator
...
ObjectAnimator xTrasnlationObjectAnimator = ObjectAnimator.ofFloat(v, view_x, _your_delta_x_);
ObjectAnimator yTrasnlationObjectAnimator = ObjectAnimator.ofFloat(v, view_y, _your_delta_y_);
animatorSet.playSequentially(xTrasnlationObjectAnimator, yTrasnlationObjectAnimator);
}
...
animatorSet.start()
to set right parameters to object animator refer the official documentation http://developer.android.com/reference/android/animation/ObjectAnimator.html
Just for the sake of completeness, i publish the actual code used to solve the problem:
// in this list you can insert as many animations you want
List<Animator> animations = new ArrayList<Animator>();
AnimatorSet animatorSet = new AnimatorSet();
ObjectAnimator xTrasnlationObjectAnimator = ObjectAnimator.ofFloat(image, View.TRANSLATION_X, (float)300);
xTrasnlationObjectAnimator.setRepeatCount(0);
ObjectAnimator yTrasnlationObjectAnimator = ObjectAnimator.ofFloat(image, View.TRANSLATION_Y, (float)300);
yTrasnlationObjectAnimator.setRepeatCount(0);
ObjectAnimator x2TrasnlationObjectAnimator = ObjectAnimator.ofFloat(image, View.TRANSLATION_X, (float)400);
x2TrasnlationObjectAnimator.setRepeatCount(0);
animations.add(xTrasnlationObjectAnimator);
animations.add(yTrasnlationObjectAnimator);
animations.add(x2TrasnlationObjectAnimator);
animatorSet.playSequentially(animations);
animatorSet.start();

Android ValueAnimator pauses during repeat

So I'm using a ValueAnimator to animate a stick figure's limbs from one position to another, in an infinite loop, or at least until the animation is stopped. My problem is that when the animator repeats I have a slight pause as if the animation is lagging behind, but it only happens when the animation repeats. I have other animations that only happen once and those run perfectly smoothly, and they have just as much computation each time so I'm currently thinking that it's a problem with the ValueAnimator.
In the past I was able to find other people complaining about this problem, but I haven't been able to find anyone who has found a solution. Do you guys know if this is a real problem with the Android ValueAnimator? If so, do you know of any solutions? If not, do you guys have any ideas as to why this could be happening to me in just that one place in the animation? I'm really stuck on this one.
My code for the ValueAnimator setup is this:
mFigureAnimator = ValueAnimator.ofFloat(0f, 1f);
mFigureAnimator.setInterpolator(new LinearInterpolator());
mFigureAnimator.setDuration(1000);
mFigureAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
public void onAnimationUpdate(ValueAnimator animation) {
Float delta = (Float)animation.getAnimatedValue();
// Set the drawn locations based on the animated time and the start/end
invalidate();
}
});
mFigureAnimator.setRepeatCount(ValueAnimator.INFINITE);
mFigureAnimator.setRepeatMode(ValueAnimator.RESTART);
mFigureAnimator.start();
for Animation, you can configure the interpolator as LinearInterpolator in the animation file :
android:interpolator="#android:anim/linear_interpolator"
for Animator, LinearInterpolator also work for me, I had a rotate animator, do 360 degrees rotation and repeat infinite:
public class RotateAnimator {
private float mDegrees;
private ObjectAnimator mAnim;
private RotateAnimator() {
mAnim = ObjectAnimator.ofFloat(this, "degrees", 360);
mAnim.setInterpolator(new LinearInterpolator());
mAnim.setRepeatCount(ValueAnimator.INFINITE);
mAnim.setRepeatMode(ValueAnimator.INFINITE);
mAnim.setEvaluator(new FloatEvaluator());
mAnim.setDuration(2000);
mAnim.start();
}
public float getDegrees() {
return mDegrees;
}
public void setDegrees(float degrees) {
this.mDegrees = degrees;
// invalidate the view so it can redraw itself
invalidate();
}
}
that way solved my problem, if you couldn't find another solution, hope this can help you, good luck.

How to stop an animation (cancel() does not work)

I need to stop a running translate animation. The .cancel() method of Animation has no effect; the animation goes until the end anyway.
How do you cancel a running animation?
Call clearAnimation() on whichever View you called startAnimation().
On Android 4.4.4, it seems the only way I could stop an alpha fading animation on a View was calling View.animate().cancel() (i.e., calling .cancel() on the View's ViewPropertyAnimator).
Here's the code I'm using for compatibility before and after ICS:
public void stopAnimation(View v) {
v.clearAnimation();
if (canCancelAnimation()) {
v.animate().cancel();
}
}
... with the method:
/**
* Returns true if the API level supports canceling existing animations via the
* ViewPropertyAnimator, and false if it does not
* #return true if the API level supports canceling existing animations via the
* ViewPropertyAnimator, and false if it does not
*/
public static boolean canCancelAnimation() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
}
Here's the animation that I'm stopping:
v.setAlpha(0f);
v.setVisibility(View.VISIBLE);
// Animate the content view to 100% opacity, and clear any animation listener set on the view.
v.animate()
.alpha(1f)
.setDuration(animationDuration)
.setListener(null);
If you are using the animation listener, set v.setAnimationListener(null). Use the following code with all options.
v.getAnimation().cancel();
v.clearAnimation();
animation.setAnimationListener(null);
You must use .clearAnimation(); method in UI thread:
runOnUiThread(new Runnable() {
#Override
public void run() {
v.clearAnimation();
}
});
What you can try to do is get the transformation Matrix from the animation before you stop it and inspect the Matrix contents to get the position values you are looking for.
Here are the api's you should look into
public boolean getTransformation (long currentTime, Transformation outTransformation)
public Matrix getMatrix ()
public void getValues (float[] values)
So for example (some pseudo code. I have not tested this):
Transformation outTransformation = new Transformation();
myAnimation.getTransformation(currentTime, outTransformation);
Matrix transformationMatrix = outTransformation.getMatrix();
float[] matrixValues = new float[9];
transformationMatrix.getValues(matrixValues);
float transX = matrixValues[Matrix.MTRANS_X];
float transY = matrixValues[Matrix.MTRANS_Y];
Use the method setAnimation(null) to stop an animation, it exposed as public method in
View.java, it is the base class for all widgets, which are used to create interactive UI components (buttons, text fields, etc.).
/**
* Sets the next animation to play for this view.
* If you want the animation to play immediately, use
* {#link #startAnimation(android.view.animation.Animation)} instead.
* This method provides allows fine-grained
* control over the start time and invalidation, but you
* must make sure that 1) the animation has a start time set, and
* 2) the view's parent (which controls animations on its children)
* will be invalidated when the animation is supposed to
* start.
*
* #param animation The next animation, or null.
*/
public void setAnimation(Animation animation)
To stop animation you may set such objectAnimator that do nothing, e.g.
first when manual flipping there is animation left to right:
flipper.setInAnimation(leftIn);
flipper.setOutAnimation(rightOut);
then when switching to auto flipping there's no animation
flipper.setInAnimation(doNothing);
flipper.setOutAnimation(doNothing);
doNothing = ObjectAnimator.ofFloat(flipper, "x", 0f, 0f).setDuration(flipperSwipingDuration);
First of all, remove all the listeners which are related to the animatior or animator set. Then cancel the animator or animator set.
inwardAnimationSet.removeAllListeners()
inwardAnimationSet.cancel()
use this way:
// start animation
TranslateAnimation anim = new TranslateAnimation( 0, 100 , 0, 100);
anim.setDuration(1000);
anim.setFillAfter( true );
view.startAnimation(anim);
// end animation or cancel that
view.getAnimation().cancel();
view.clearAnimation();
cancel()
Cancel the animation. Canceling an animation invokes the animation
listener, if set, to notify the end of the animation.
If you cancel an animation manually, you must call reset()
before starting the animation again.
clearAnimation()
Cancels any animations for this view.
After going through all the things nothing worked. As I applied multiple animations in my views.
So below is the code that worked for me.
To start the animation that fades in and fade out continuously
val mAnimationSet = AnimatorSet()
private fun performFadeAnimation() {
val fadeOut: ObjectAnimator = ObjectAnimator.ofFloat(clScanPage, "alpha", 1f, 0f)
fadeOut.duration = 1000
val fadeIn: ObjectAnimator = ObjectAnimator.ofFloat(clScanPage, "alpha", 0f, 1f)
fadeIn.duration = 1000
mAnimationSet.play(fadeIn).after(fadeOut)
mAnimationSet.addListener(animationListener)
mAnimationSet.start()
}
The animation listener that loops in continuously
private val animationListener=object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator?) {
super.onAnimationEnd(animation)
mAnimationSet.start()
}
}
To stop the animation that going on in a loop. I did the following.
private fun stopAnimation() {
mAnimationSet.removeAllListeners()
}
Since none of other answers mention it, you can easily stop an animation using ValueAnimator's cancel().
ValueAnimator is very powerful for making animations. Here is a sample code for creating a translation animation using ValueAnimator:
ValueAnimator valueAnimator = ValueAnimator.ofFloat(0f, 5f);
int mDuration = 5000; //in millis
valueAnimator.setDuration(mDuration);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
// Update your view's x or y coordinate
}
});
valueAnimator.start();
You then stop the animation by calling
valueAnimator.cancel()`

Categories

Resources