android animation while UI thread working - android

My app has certain actions which require rendering a complicated layout. During that time, I'd like to show an animation. I'm trying to handle the animation in dispatchDraw(), but since the rendering is taking a long time the UI dispatchDraw() never gets a chance to execute. (It would be nice to optimize that but that isn't my priority right now.)
This is the essential part of my animation code:
ValueAnimator animator = ValueAnimator.ofFloat (1f, 2f);
animator.setDuration (1000);
animator.addUpdateListener (new ValueAnimator.AnimatorUpdateListener()
{
public void onAnimationUpdate (ValueAnimator animation)
{
zoomScale = (float) animation.getAnimatedValue ();
invalidate ();
}
});
Is there a way to draw directly during the onAnimationUpdate(), rather than relying on invalidate()?
Or, alternatively, is there a way to relinquish the UI thread during a long onLayout()?

Related

Trying to reset values from Property Animator to be used in recycler view

Been doing some animation inside of a row in RecyclerView (not the row itself. Imagine expanding text) and there are times when the animation leaks to other recycled views which should not have that animation in them.
Since I use property animation the scale action resizes the inner view and the leak can be seen in 2 aspects:
1) The animation will go on (This I could overcome with some guards)
2) The view has been resized and stopped in its tracks and so it will be reflected in the recycled view.
How can I reset the views to their original state? I have tried many approaches from posts but none solved it. The closest definition I got was in this unanswered post:
How to reset view to original state after using animators to animates its some properties?
Here is a sample of how I set up my animation in onBind (this one has an attempt to use onAnimationEnd which I found in one post but did not work)
ObjectAnimator scaleXUp = ObjectAnimator.ofFloat(mView, View.SCALE_X, 10f);
scaleXUp.setRepeatCount(ValueAnimator.INFINITE);
scaleXUp.setRepeatMode(ValueAnimator.REVERSE);
scaleXUp.setDuration(700);
ObjectAnimator scaleYUp = ObjectAnimator.ofFloat(mView, View.SCALE_Y, 10f);
scaleYUp.setRepeatCount(ValueAnimator.INFINITE);
scaleYUp.setRepeatMode(ValueAnimator.REVERSE);
scaleYUp.setDuration(700);
mTotalAnimation = new AnimatorSet();
mTotalAnimation.play(scaleXUp).with(scaleYUp);
mTotalAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
mTotalAnimation.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
animation.removeListener(this);
animation.setDuration(0);
for(Animator va : ((AnimatorSet)animation).getChildAnimations()) {
((ValueAnimator)va).reverse();
}
}
});
mTotalAnimation.start();
And here is what I do in the onUnbindData:
if (mTotalAnimation != null) {
mTotalAnimation.end();
mTotalAnimation = null;
}
And as I saw many people like the clearAnimation approach - tried and did not work either.
4 days and not one response but meanwhile I solved it myself.
So the approach was close, just wrongly placed.
I added this method:
private void stopAnimation() {
for (Animator anim : mTotalAnimation.getChildAnimations()) {
((ObjectAnimator) anim).reverse();
anim.end();
}
}
and I call that when I want to reset the view.
Here I am getting the animations from the AnimatorSet and reversing and ending each. I did not understand why I had to do it manually but it looks like this ability will be added in Android O:
https://developer.android.com/preview/api-overview.html#aset
Starting in Android O, the AnimatorSet API now supports seeking and playing in reverse. Seeking lets you set the position of the animation set to a specific point in time. Playing in reverse is useful if your app includes animations for actions that can be undone. Instead of defining two separate animation sets, you can play the same one in reverse.

Options for endlessly repeating function GUI calls while remaining responsive

I've got an animation to perform which consists of some arrow heads aligned horizontally where the alpha values of the arrows will change to achieve an animation effect (i.e. first arrow has alpha 1.0, then the second will get a value 1.0 etc.).
So if I have a function like this:
void highlightFirstArrow()
{
mArrow1.setAlpha(1.0f);
mArrow2.setAlpha(0.75f);
mArrow3.setAlpha(0.50f);
mArrow4.setAlpha(0.20f);
}
Then I'd want to start, repeat numerous times, then stop a function such as this:
void animateArrows()
{
highlightFirstArray();
pause;
highlightSecondArray();
pause;
etc.
}
Obviously this would lock up the GUI thread if it were performed in a for look for example. What are the options for achieving the desired animiation:
- run a for loop in a separate thread
- don't use a loop, instead constantly execute the functions individually via a timer
- use built in specific android animation mechanisms. If so which is most appropriate? Would AnimatorSet() be good for this scenario, or something else
You definitely shouldn't use any loops or timers. There're lots of built in classes which could help to animate your views. For instance you can use ValueAnimator:
ValueAnimator.ofFloat(1f, 0.2f).setDuration(1000).addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override public void onAnimationUpdate(ValueAnimator animation) {
float value = (float) animation.getAnimatedValue();
arrow1.setAlpha(value);
arrow2.setAlpha(value);
}
});

Setting end values without animation with AnimatorSet

According to the documentation http://developer.android.com/reference/android/animation/AnimatorSet.html#end() end() method should assign the end values for all animations inside the set. However ending does nothing if the set was not started. This is different from ValueAnimator i.e. which does not care and artifically starts the animation, fires onAnimationStart() event and then ends it which results in setting the end values properly.
Let me tell you why this is a problem. If you want to have the ability to update your View with and without animation (depending on the situation) you don't want to have two separate methods for it. Instead you could create an animation and start it normally or immediately set the end values. With ValueAnimator this works nicely. However AnimatorSet does not play ball and if you try to end it before calling start() it simply exits.
One workaround for this is to call start() and end() immediately after but it does not cover the situation with nested AnimatorSets like this:
AnimatorSet mainSet = new AnimatorSet();
AnimatorSet scaleSet = new AnimatorSet();
scaleSet.playTogether(
ObjectAnimator.ofFloat(view, "scaleX", 0.5f),
ObjectAnimator.ofFloat(view, "scaleY", 0.5f));
mainSet.playSequentially(
ObjectAnimator.ofFloat(view, "alpha", 0.5f),
scaleSet);
mainSet.start();
mainSet.end();
This causes the mainSet to call end() on all its children. But since AnimatorSet.end() is broken the scaleSet does not set ending values. I attempted to extend AnimatorSet class and fix this but soon found out it is marked final.
In my app I mostly use animations but have some few cases where animations are not needed. Does anyone have an idea how to achieve the proper behaviour?
You can do that on all child animations with:
for (Animator animation : mainSet.getChildAnimations())
{
animation.start();
animation.end();
}
I know this is an old question but a recursive approach can solve this:
void endAnimationsRecursively(final Animator mainAnimator){
if (mainAnimator instanceof AnimatorSet) {
for (final Animator animator : ((AnimatorSet)
mainAnimator).getChildAnimations()) {
endAnimationsRecursively(animator);
}
mainAnimator.end();
mainAnimator.cancel();
}
}

Why validate on View does not work but postInvalidate works

I have a card a game in which the person chooses the card and drags (done through translate animation) and then when let go it moves to the center of the screen where have an imageView place holder. At the animationEnd I set the image view to that card and can invalidate on each view on the screen. What I dont understand is that when I call invalidate then the card looks like it left some trails (shadows from the translate animation). When I call postInvalidate, it gets drawn properly. Why is that??
AnimationEnd code:
#Override
public void onAnimationEnd(Animation arg0) {
if(card == null){
MyApplication.SWERR(null);
busy = false;
}
card.getCardImage().setVisibility(View.INVISIBLE);
Drawable drawable = card.getCardSuitNumber().getDrawable(mContext);
finalDestIV.setBackgroundDrawable(drawable);
finalDestIV.setVisibility(View.VISIBLE);
invalidateAll();
PlayerStatus p = mGameMonitor.getPlayerStatusFromPlayerEnum(GameConstants.PLAYERS.P1);
p.handleCardChosen(card);
cardReleased = false;
p.setPlayerLock(false);
card = null;
}
InvalidateAll method
private void invalidateAll(){
rootLayout.postInvalidate();
for (int i=0; i<rootLayout.getChildCount();i++){
View v = rootLayout.getChildAt(i);
v.postInvalidate();
}
}
Typical problem of novice Android developers.
Please look into the description of the invalidate method.
According to the Google documentation:
Invalidate the whole view. If the view is visible, onDraw(android.graphics.Canvas) will be called at some point in the future. This must be called from a UI thread. To call from a non-UI thread, call postInvalidate().
So, I suppose onAnimationEnd is calling from non-UI thread (probably animation thread).
I think if you avoid the API policy it may lead to unexpected behavior and may differs between different Android versions.
Calling invalidate from non-UI thread can interrupt some UI operations (or brake some logic) in Android system which makes some misbehavior.
Look also here: What does postInvalidate() do?

Using animation on a ViewPager and setFillAfter

I have a ViewPager which I need to move as a whole on button press. I use an animation for this.
When I press it, I translate the 'x' for it. I use setFillAfter(true) to keep the new position.
But when I change the page of the ViewPager, it jumps back to the original x-position!
I only saw this issue on Android 4.1, with Android 4.0 there is no problem! So it looks like some kind of regression in Android.
I attached a testproject where I could reproduce the issue without all my other stuff around it. I think it is best if you want to help me figure this out to import the project in your Eclipse and see it for yourself.
I also added to video's, one on my HTC One X where I see the issue, and the other on a tablet with Android 4.0, where the issue is not there.
I have been desperately looking to fix this ugly side effect, but no luck till now...
(Sorry for the big movie files...)
Video of Android 4.0 without the side effect
Video Android 4.1 with the side effect
the project where you can reproduce the issue with
Edit:
I added the following:
#Override
public void onAnimationEnd(Animation animation) {
RelativeLayout.LayoutParams lp = (android.widget.RelativeLayout.LayoutParams) myViewPager.getLayoutParams();
if (!i)
lp.setMargins(300,0,0,0);
else
lp.setMargins(0,0,0,0);
myViewPager.setLayoutParams(lp);
}
After that it stays at the correct position, but it 'flickers' quickly, like the animation is still showing at the end and when I change the margin, it still shows the offset it had after animation. Then it jumps to the correct position.
The main problem seems to be incorrect choice of animation type. You see, View Animation as a tool is not intended to be used with complex interactive objects like ViewPager. It offers only low-cost animation of the drawing place of views. The visual behaivior of the animated ViewPager in response to user-actions is undefined and should not be relied on.
Ugly flicks, when you substitute a "gost" with the real object are only natural.
The mechanism, that is intended to use in your case since API 11 is specialized property animator built in Views for optimized performance: ViewPropertyAnimator, or not specialized, but more versatile ObjectAnimator and AnimatorSet.
Property animation makes the View to really change its place and function normally there.
To make project, to use, say, ViewPropertyAnimator, change your listener setting to this:
btn.setOnClickListener(new OnClickListener() {
boolean b = false;
#Override
public void onClick(View v) {
if(b) {
myViewPager.animate().translationX(0f).setDuration(700);
}
else {
myViewPager.animate().translationX(300f).setDuration(700);
}
b=!b;
}
});
If you want to use xml configuration only, stick to |ObjectAnimator and AnimatorSet. Read through the above link for further information.
In case, you are anxious to support pre-Honeycomb devices, you can use Jake Warton's NineOldAndroids project. Hope that helps.
That's because the Animation's setFillAfter(true) doesn't actually change the position or any attributes of the View; all it does is create a Bitmap of the view's drawing cache and leaves it where the animation ends. Once the screen is invalidated again (ie. changing the page in the ViewPager), the bitmap will be removed and it will appear as if the View is returning to it's original position, when in fact it was already there.
If you want the View to retain it's position after the animation has finished, you need to actually adjust the View's LayoutParams to match your desired effect. To achieve this, you can override the onAnimationEnd method of the Animation, and adjust the LayoutParams of the View inside there.
Once you adjust the LayoutParams, you can remove your call to setFillAfter(true) and your View will actually stay where you expect it to.
Regarding the flicker issue:
I have encountered this issue before, and it stems from the possibility of the onAnimationEnd() call not syncing up with the next layout pass. Animation works by applying a transformation to a View, drawing it relative to its current position.
However, it is possible for a View to be rendered after you have moved it in your onAnimationEnd() method. In this case, the Animation's transformation is still being applied correctly, but the Animation thinks the View has not changed its original position, which means it will be drawn relative to its ENDING position instead of its STARTING position.
My solution was to create a custom subclass of Animation and add a method, changeYOffset(int change), which modifies the y translation that is applied during the Animation's applyTransformation method. I call this new method in my View's onLayout() method, and pass the new y-offset.
Here is some of my code from my Animation, MenuAnimation:
/**
* Signal to this animation that a layout pass has caused the View on which this animation is
* running to have its "top" coordinate changed.
*
* #param change
* the difference in pixels
*/
public void changeYOffset(int change) {
fromY -= change;
toY -= change;
}
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
float reverseTime = 1f - interpolatedTime;
float dy = (interpolatedTime * toY) + (reverseTime * fromY);
float alpha = (interpolatedTime * toAlpha) + (reverseTime * fromAlpha);
if (alpha > 1f) {
alpha = 1f;
}
else if (alpha < 0f) {
alpha = 0f;
}
t.setAlpha(alpha);
t.getMatrix().setTranslate(0f, dy);
}
And from the View class:
private int lastTop;
// ...
#Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
// the animation is expecting that its View will not be moved by the container
// during its time period. if this does happen, we need to inform it of the change.
Animation anim = getAnimation();
if (anim != null && anim instanceof MenuAnimation) {
MenuAnimation animation = (MenuAnimation) anim;
animation.changeYOffset(top - lastTop);
}
// ...
lastTop = top;
super.onLayout(changed, left, top, right, bottom);
}
Crucero has it right about setFillAfter not adjusting params post invalidation. When the view is re-layed out (which'll happen the pass after it's invalidated), its layout params will be the ones that always applied, so it should go back to the original position.
And Jschools is right about onAnimationEnd. Strongly encourage you to step through the source code with a debugger, where you'll instructively discover that an update is made that affects the drawn position of the view after onAnimationEnd is fired, at which point you've actually applied the layout params, hence the flicker caused by doubled up offset.
But this can be solved quite simply by making sure you relayout at the right time. You want to put your re-positioning logic at the end of the ui message queue at the time of animation end so that it is polled after the animation but before laying out. There's nowhere that suggests doing this, annoyingly, but I've yet find a reason in any release of the SDK reason why (when doing this just once and not incorrectly using ui thread) this shouldn't work.
Also clear the animation due to another issue we found on some older devices.
So, try:
#Override
public void onAnimationEnd(final Animation animation) {
myViewPager.post(new Runnable() {
#Override
public public void run() {
final RelativeLayout.LayoutParams lp = (android.widget.RelativeLayout.LayoutParams) myViewPager.getLayoutParams();
if (!someBooleanIPresume)
lp.setMargins(300,0,0,0);
else
lp.setMargins(0,0,0,0);
myViewPager.setLayoutParams(lp);
myViewPager.clearAnimation();
}
}

Categories

Resources