Android ObjectAnimato is cancelled before the end - android

I have a fragment with 3 LinearLayout inside. By default, the first one have the weight attribute to 1.
Each LinearLayout have a OnClickListener that trigger 2 animations:
Animation with a weight from 0 to 1 for the one that is clicked.
Animation with a weight from 1 to 0 for the one currently opened.
My problem is that sometime the animations are not finishing completely.
Here is the code triggered by the OnClickListener:
private void launchAnimation(final LinearLayout llToExpand) {
ViewWeightAnimationWrapper animationWrapper = new ViewWeightAnimationWrapper(llToExpand);
ObjectAnimator anim = ObjectAnimator.ofFloat(animationWrapper,
"weight",
animationWrapper.getWeight(),
1f);
anim.setDuration(1000);
anim.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
Log.d("Anim1", "onAnimationEnd: Anim1 have ended");
}
#Override
public void onAnimationCancel(Animator animation) {
Log.d("Anim1", "onAnimationCancel: Anim1 have been canceled.");
}
});
ViewWeightAnimationWrapper animationWrapper2 = new ViewWeightAnimationWrapper(mLlCurrentlyOpened);
ObjectAnimator anim2 = ObjectAnimator.ofFloat(animationWrapper2,
"weight",
animationWrapper2.getWeight(),
0f);
anim2.setDuration(1000);
anim2.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
Log.d("Anim2", "onAnimationEnd: Anim2 have ended");
mLlCurrentlyOpened = llToExpand;
}
#Override
public void onAnimationCancel(Animator animation) {
Log.d("Anim2", "onAnimationCancel: Anim2 have been canceled.");
}
});
anim.start();
anim2.start();
}
Here is the code of my ViewWeightAnimationWrapper:
public class ViewWeightAnimationWrapper {
private View view;
public ViewWeightAnimationWrapper(View view) {
if (view.getLayoutParams() instanceof LinearLayout.LayoutParams) {
this.view = view;
} else {
throw new IllegalArgumentException("The view should be a LinearLayout");
}
}
public void setWeight(float weight) {
Log.i(String.valueOf(view.getId()), "setWeight: " + weight);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
params.weight = weight;
view.requestLayout();
}
public float getWeight() {
return ((LinearLayout.LayoutParams) view.getLayoutParams()).weight;
}
Here are the log that I have when the animation isn't going to the end:
I/2131755212: setWeight: 0.5
I/2131755207: setWeight: 0.5
I/2131755212: setWeight: 0.5251222
I/2131755207: setWeight: 0.47487777
I/2131755212: setWeight: 0.55174345
I/2131755207: setWeight: 0.44825655
D/Anim1: onAnimationCancel: Anim1 have been canceled.
D/Anim1: onAnimationEnd: Anim1 have ended
D/Anim2: onAnimationCancel: Anim2 have been canceled.
D/Anim2: onAnimationEnd: Anim2 have ended
I have no clue about why my animation are not canceled every time.
How can I know what is canceling my animations? Is it possible to force the animations to finish when they are cancelled?

I haven't found the reason about why the animation is canceled.
On the documentation, they say that the animation is canceled when there the same animation is triggered on the same object, which wasn't my case.
However, i have found a workaround here that is giving me the expected result.
I have replaced the ObjectAnimator by a custom animation:
/**
* Launch the expand animation on the LinearLayout in parameter and launch the folding animation
* on the currently opened LinearLayout.
* #param llToExpand LinearLayout that we want to expand.
*/
private void launchAnimation(final LinearLayout llToExpand) {
// Create the and assign the animations
ExpandAnimation expand = new ExpandAnimation(llToExpand, 0, 1);
expand.setDuration(500);
ExpandAnimation fold = new ExpandAnimation(mLlCurrentlyOpened, 1, 0);
fold.setDuration(500);
// Start the animations
llToExpand.startAnimation(expand);
mLlCurrentlyOpened.startAnimation(fold);
// Switch the currently opened LinearLayout for the next time
mLlCurrentlyOpened = llToExpand;
}
Here is my ExpandAnimation:
public class ExpandAnimation extends Animation {
private float mStartWeight;
private final float mEndWeight;
private final LinearLayout mContent;
public ExpandAnimation(LinearLayout content, float startWeight,
float endWeight) {
mStartWeight = startWeight;
mEndWeight = endWeight;
mContent = content;
}
#Override
protected void applyTransformation(float interpolatedTime,
Transformation t) {
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mContent
.getLayoutParams();
mStartWeight = lp.weight;
lp.weight = (mStartWeight + ((mEndWeight - mStartWeight) * interpolatedTime));
mContent.setLayoutParams(lp);
}
#Override
public boolean willChangeBounds() {
return true;
}
}

I just ran into what might be the same issue. Looking at the ObjectAnimator source, it's holding a WeakReference to the animation target. In my case I was using a dedicated object created only to perform the animation, and it turned out that the weak reference was the only reference. Thus it would sometimes be de-referenced during the animation. ObjectAnimator handles this "cleanly", simply canceling the animation.

Related

How to playSequentially a list of AnimatorSet?

I'm trying to make an animation of an imageview that revolves around a circle shape.
Here is the currrent code who works but without repeating the animation with different values:
public void runAnimation(){
ImageView worldView=findViewById(R.id.imageView);
int radius=worldView.getHeight()*30/70;
int centerx = worldView.getLeft()+radius;
int centery = worldView.getTop()+radius;
//List<Animator> myList = new ArrayList<>();
for (int i=0;i<360;i++) {
/*---I calculate the points of the circle---*/
int angle= (int) ((i * 2 * Math.PI) / 360);
int x= (int) (centerx+(radius*Math.cos(angle)));
int y= (int) (centery+(radius*Math.sin(angle)));
/*---Here carView is the ImageView that need to turn around the worldView---*/
ObjectAnimator animatorX =ObjectAnimator.ofFloat(carView, "x",x);
ObjectAnimator animatorY =ObjectAnimator.ofFloat(carView, "y",y);
ObjectAnimator animatorR =ObjectAnimator.ofFloat(carView, "rotation", i);
animatorX.setDuration(500);
animatorY.setDuration(500);
animatorR.setDuration(500);
AnimatorSet animatorSet=new AnimatorSet();
animatorSet.playTogether(animatorX,animatorY,animatorR);
animatorSet.start();
//myList.add(animatorSet);
}
//AnimatorSet animatorSet=new AnimatorSet();
//animatorSet.playSequentially(myList);
}
The commentary ("//") are here to illustrate what I want to create.
Thank in advance for your help.
You can add a listener to each AnimatorSet by using addListener(Animator.AnimatorListener listener).
for (int i=0;i<360;i++) {
// ...skipped some lines here...
AnimatorSet animatorSet=new AnimatorSet();
animatorSet.playTogether(animatorX,animatorY,animatorR);
myList.add(animatorSet);
animatorSet.addListener(myListener);
}
where myListener is defined as follows:
private Animator.AnimatorListener myListener = new Animator.AnimatorListener(){
#Override
public void onAnimationStart(Animator animation){
// no op
}
#Override
public void onAnimationRepeat(Animator animation){
// no op
}
#Override
public void onAnimationCancel(Animator animation){
// no op
}
#Override
public void onAnimationEnd(Animator animation){
startNextAnimation();
}
};
In addition to that, you need some variable private int counter; to iterate over the list.
Before starting the first animation, you set it to zero:
counter = 0;
myList.get(0).start();
To start the next animation (if there is one left):
private void startNextAnimation(){
counter++;
if(counter == myList.size()){
return;
}
myList.get(counter).start();
}

Looping animated ScrollView in Android pauses between repeats

I'm implementing a slot machine in Android. The reels are ScrollViews with LinearLayouts as children, and the individual tiles as ImageViews vertically oriented inside the LinearLayout. I'm using an ObjectAnimator to scroll to the end of the ScrollView, using ValueAnimator.RESTART and ValueAnimator.INFINITE. The reel scrolling is nice and smooth, however when it comes time to repeat, it pauses for a second, which ruins the effect. Here's the code I'm using:
public void spinReel(SlotReel reel) {
final int reelSize = this.context.getPixelsInDPs(64);
final SlotMachineView me = this;
final SlotReel myReel = reel;
ImageView[] tiles = reel.getTiles();
int delta = tiles.length - reel.currentTileNumber();
ObjectAnimator animator = ObjectAnimator.ofInt(reel, "scrollY", tiles.length * reelSize );
animator.setInterpolator(new LinearInterpolator());
animator.setDuration(delta * 75);
animator.setStartDelay(0);
animator.setRepeatMode(ValueAnimator.RESTART);
animator.setRepeatCount(ValueAnimator.INFINITE);
animator.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animator) {
}
#Override
public void onAnimationEnd(Animator animator) {
}
#Override
public void onAnimationCancel(Animator animator) {
}
#Override
public void onAnimationRepeat(Animator animator) {
myReel.scrollTo(0, reelSize * 3);
}
});
animator.start();
}
Note that the jerkiness occurs whether or not I put the scrollTo in the Repeat callback.
Example video here:
You should try:
setRepeatMode(ValueAnimator.INFINITE);
look here
Android ValueAnimator pauses during repeat

Animating Android ListView header height causes flicker at the end of animation

Problem
I'm trying to animate the ListView header height. I can get the animation right, but after the animation completes the ListView flickers.
Tried and failed
Use AnimationSet.setFillAfter() without changing the layout params. The animation works fine, but when you start scrolling the list, header jumps back to original position.
Use AnimationSet.setFillAfter() with new layout params applied at onAnimationEnd(). After the animation ends the header jumps to twice the required height (animated height plus the height set in layout params). When you start scrolling the list, header snaps to the required height.
Code
if (mSearchAdapter.getCount() > 0 && mListView.getChildAt(0) == mHeaderPlaceholder) {
Log.i(TAG, "Animating list view to make room for info bar");
AnimationSet slideAnimation = new AnimationSet(true);
TranslateAnimation translate = new TranslateAnimation(0, 0, 0, newHeight);
translate.setDuration(mInfoBarAnimationDuration);
translate.setInterpolator(new DecelerateInterpolator());
slideAnimation.addAnimation(translate);
slideAnimation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
isAnimatingViewTransition = true;
}
#Override
public void onAnimationEnd(Animation animation) {
isAnimatingViewTransition = false;
final AbsListView.LayoutParams layoutParams = (AbsListView.LayoutParams) mHeaderPlaceholder.getLayoutParams();
layoutParams.height = newHeight;
mHeaderPlaceholder.setLayoutParams(layoutParams);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
mListView.startAnimation(slideAnimation);
} else {
Log.i(TAG, "Adjusting list view header to make room for info bar");
mHeaderPlaceholder.getLayoutParams().height = newHeight;
}
I think the flicker can be avoided by listening for and overriding the events onPreDraw() or onGlobalLayout() of the ViewTreeObserver of the ListView. But I don't know exactly how I can achieve it.
Any help is much appreciated!
Instead of animating ListView header I opted to used ValueAnimator to achieve the same effect. Here is code:
if (mSearchAdapter.getCount() > 0 && mListView.getChildAt(0) == mHeaderPlaceholder) {
ValueAnimator mSlideListViewAnimator = ObjectAnimator.ofInt(from, to);
mSlideListViewAnimator.setDuration(mInfoBarAnimationDuration);
mSlideListViewAnimator.setInterpolator(new DecelerateInterpolator());
mSlideListViewAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
Integer animatedYValue= (Integer) animation.getAnimatedValue();
final AbsListView.LayoutParams layoutParams = (AbsListView.LayoutParams) mHeaderPlaceholder.getLayoutParams();
layoutParams.height = animatedYValue;
mHeaderPlaceholder.requestLayout();
}
});
mSlideListViewAnimator.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationStart(Animator animation) {
isAnimatingViewTransition = true;
}
#Override
public void onAnimationEnd(Animator animation) {
isAnimatingViewTransition = false;
}
});
mSlideListViewAnimator.start();
} else {
Log.i(TAG, "Adjusting list view header to make room for info bar");
mHeaderPlaceholder.getLayoutParams().height = newHeight;
}

Android Multiple AnimatorSet reset

Hi I am applying multiple animations to a view using AnimatorSet and ValueAnimator.
When the user touches the view, successive animations are applied to the view. I do this to have a "zooming effect" when the user is moving his fingers on the view.
The view is a custom gallery.
Here is the code for animation:
private void createAnim(final View v) {
animating = true;
if (D)
Log.i(TAG, "sarting animation");
try {
v.clearAnimation();
v.getAnimation().reset();
} catch (Exception e) {
}
set = new AnimatorSet();
set.addListener(new AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
if (D)
Log.i(TAG, "Animation ended");
animating = false;
}
#Override
public void onAnimationCancel(Animator animation) {
animating = false;
if (D)
Log.i(TAG, "Animation cancelled");
}
});
set.setDuration(100);
ValueAnimator v1 = ObjectAnimator.ofFloat(v, "scaleX", mScaleFactor);
ValueAnimator v2 = ObjectAnimator.ofFloat(v, "scaleY", mScaleFactor);
animationList.add(v1);
animationList.add(v2);
set.playTogether(v1, v2);
set.start()
}
I have an onTouchListener and on action move I successively call this method increasing or decreasing the mScaleFactor.
When the user releases the finger I would like the view to go back to previous state, I mean to erase all animations applied as if they were never applied to view. The problem is you can easily do that for one animation but for many like that I just can't find the right way. Here is what I have tried:
-Adding the animations to an ArrayList and doing animation.reverse() on each one of them with a delay of +100 added to each of them so the execute one after another but the end result just doesn't seem exactly the same as before animations.
v.clearAnimation(); only cancels the last animation
v.getAnimation().reset(); same only works for last/active animation.
Is there a method to just get the view back as it was before any animation has been started?
Thanks a lot
Reversing the effects of an AnimatorSet can be tricky simply because there is no "reverse" method. The easiest method in this case, would probably simply be another AnimatorSet that does the opposite of the original. The issue here would be is your AnimatorListener could be out of sync. If you do this way and you want to keep the boolean, then you'd have to implement it as somewhat of a semaphore.
public static class AnimatorTracker implements AnimatorListener{
int counter;
public AnimatorTracker() {
counter = 0;
}
public boolean isAnimating() {
return counter == 0;
}
#Override
public void onAnimationStart(Animator animation) {
counter++;
}
#Override
public void onAnimationRepeat(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
counter--;
}
#Override
public void onAnimationCancel(Animator animation) {
// Canceling an animation invokes onAnimationEnd, so nothing needs to be done.
}
}
Then just make the sets the same way you just did:
AnimatorTracker tracker = new AnimatorTracker(); // or make it a global reference
AnimatorSet set = new AnimatorSet();
AnimatorSet reverseSet = new AnimatorSet();
ValueAnimator v1 = ObjectAnimator.ofFloat(v, "scaleX", mScaleFactor);
ValueAnimator v2 = ObjectAnimator.ofFloat(v, "scaleY", mScaleFactor);
ValueAnimator reverseV1 = ObjectAnimator.ofFloat(v, "scaleX", 1.0f);
ValueAnimator reverseV2 = ObjectAnimator.ofFloat(v, "scaleY", 1.0f);
set.addListener(tracker);
set.setDuration(100);
set.playTogether(v1, v2);
reverseSet.addListener(tracker);
reverseSet.setDuration(100);
reverseSet.playTogether(reverseV1, reverseV2);
Call set.start() when you want to animate forward. Call reverseSet.start() when you want to animate back.

Move an ImageView to different a position using animation in Android

I have several ImageViews in a RelativeLayout.
When the user taps any of the ImageViews, I want the ImageView to be moved to a specified location using a subtle animation.
Eg; I have initially set margins for LayoutParams associated with an ImageView as layoutparams1.setMargins(90,70,0,0); and I have then added it to the layout.
When the ImageView is tapped, I'd like its new location to be 200,200, done with animation.
So, is it possible? if yes, then how?
Note that I have both RelativeLayout and all of its child ImageViews created programmatically.
And I'm new to Android development so an elaborative answer is expected.
TranslateAnimation animation = new TranslateAnimation(0, 50, 0, 100);
animation.setDuration(1000);
animation.setFillAfter(false);
animation.setAnimationListener(new MyAnimationListener());
imageView.startAnimation(animation);
UPDATE :
The problem is that the View is actually still in it's old position. So we have to move it when the animation is finished. To detect when the animation is finished we have to create our own animationListener (inside our activity class):
private class MyAnimationListener implements AnimationListener{
#Override
public void onAnimationEnd(Animation animation) {
imageView.clearAnimation();
LayoutParams lp = new LayoutParams(imageView.getWidth(), imageView.getHeight());
lp.setMargins(50, 100, 0, 0);
imageView.setLayoutParams(lp);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
#Override
public void onAnimationStart(Animation animation) {
}
}
So the onClickEvent will get fired again at it's new place.
The animation will now move it even more down, so you might want to save the x and y in a variable, so that in the onAnimationEnd() you move it not to a fix location.
It is better to use ObjectAnimator which actually moves the ImageView to the new position.
E.g.:
ImageView splash;
#Override
public boolean onTouchEvent(MotionEvent event) {
float tx = event.getX();
float ty = event.getY();
int action = event.getAction();
switch(action) {
case MotionEvent.ACTION_DOWN:
tx = event.getX();
ty = event.getY();
// findViewById(R.id.character).setX(tx-45);
// findViewById(R.id.character).setY(ty-134);
ObjectAnimator animX = ObjectAnimator.ofFloat(splash, "x", tx-45);
ObjectAnimator animY = ObjectAnimator.ofFloat(splash, "y", ty-134);
AnimatorSet animSetXY = new AnimatorSet();
animSetXY.playTogether(animX, animY);
animSetXY.start();
break;
default:
}
return true;
}
you can use this code
imageView.animate().x(80).y(212).setDuration(300);
or
for soft animation you can use this library
https://github.com/wirecube/android_additive_animations
In below code I am adding a image view in center on frame layout dynamically. After add I am increase scaling and set alpha to give zoom effect and after complete animation I am just translate my image view one position to another position.
Add image view on framelayout
imgHeart = new ImageView(getBaseContext());
imgHeart.setId(R.id.heartImage);
imgHeart.setImageResource(R.drawable.material_heart_fill_icon);
imgHeart.setLayoutParams(new FrameLayout.LayoutParams(50, 50, Gravity.CENTER));
mainFrameLaout.addView(imgHeart);
Add animation on image view
imgHeart.animate()
.scaleXBy(6)
.scaleYBy(6)
.setDuration(700)
.alpha(2)
.setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
imgHeart.animate()
.scaleXBy(-6f).scaleYBy(-6f)
.alpha(.1f)
.translationX((heigthAndWidth[0] / 2) - minusWidth)
.translationY(-((heigthAndWidth[1] / 2) - minusHeight))
.setDuration(1000)
.setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
// remove image view from framlayout
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
}).start();
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
}).start();
you can use this code :)
private void animeView(View imageView){
Handler handler = new Handler();
final int[] deltaX = {50};
final int[] deltaRotation = {45};
handler.postDelayed(new Runnable() {
#Override
public void run() {
imageView.animate().translationX(deltaX[0])
.rotation(deltaRotation[0]).setDuration(1000) ;
deltaX[0] *=-1 ;
deltaRotation[0] *=-1 ;
handler.postDelayed(this , 1000);
}
},1000);
}

Categories

Resources