Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animation not starting until UI updates or touch event

I have a strange problem with an AlphaAnimation. It is supposed to run repeatedly when an AsyncTask handler is called.

However, the first time the handler is called in the Activity, the animation won't start unless I touch the screen or if the UI is updated (by pressing the phone's menu button for example).

The strange part is that once the animation has run at least once, it will start without problem if the handler is called again.

Here's what the code looks like:

// AsyncTask handler public void onNetworkEvent() {   this.runOnUiThread(new Runnable() {     @Override     public void run()     {       flashScreen(Animation.INFINITE);     }   }); }  // Called method private void flashScreen(int repeatCount) {   final View flashView = this.findViewById(R.id.mainMenuFlashView);    AlphaAnimation alphaAnimation = new AlphaAnimation(1, 0);   alphaAnimation.setRepeatCount(repeatCount);   alphaAnimation.setRepeatMode(Animation.RESTART);   alphaAnimation.setDuration(300);   alphaAnimation.setInterpolator(new DecelerateInterpolator());   alphaAnimation.setAnimationListener(new Animation.AnimationListener() {     @Override     public void onAnimationStart(Animation animation)     {       flashView.setVisibility(View.VISIBLE);     }      @Override     public void onAnimationEnd(Animation animation)     {       flashView.setVisibility(View.GONE);     }      @Override     public void onAnimationRepeat(Animation animation) { }   });    flashView.startAnimation(alphaAnimation); } 

I have noticed that runOnUIThread isn't necessary (same results occur if I don't use it), but I prefer keeping it as I'm not on the UI thread.

Any ideas on what could cause this?

like image 829
Jukurrpa Avatar asked Apr 26 '13 14:04

Jukurrpa


2 Answers

A little more research showed that my problem was the same a this question: Layout animation not working on first run

The flashView's visibility was set to GONE by default (causing the Animation not to start immediately as the View had never been rendered), so I just need to set it to INVISIBLE before calling flashView.startAnimation()

like image 82
Jukurrpa Avatar answered Sep 21 '22 09:09

Jukurrpa


If setting the View to VISIBLE won't work, as was in my case, it helped for me to call requestLayout() before starting the Animation, like so:

Animation an = new Animation() { ...    view.requestLayout(); view.startAnimation(an); 

In my case, my View was 0dip high which prevented onAnimationStart from being called, this helped me around that problem.

like image 31
Zebaz Avatar answered Sep 21 '22 09:09

Zebaz