androidandroid-animationtransitiondrawable

Android: Set TransitionDrawable to show the same image when activity resumes?


I'm using a TransitionDrawable to create a cross-fade animation for a button. When pressed once, the button turns on my service and the transition occurs. When pressed again, the button turns off my service and the reverse transition occurs. The xml code for this transition is as follows:-

<?xml version="1.0" encoding="UTF-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/main_off" />
    <item android:drawable="@drawable/main_on" />
</transition>

The issue is that when the activity is paused, once it resumes the TransitionDrawable reverts to the Drawable main_off (i.e. the one at index/layer 0). I can check if my service is running in onResume(), so my flag variable is ready. What I can't manage is how to set the TransitionDrawable to one of the Drawables in that xml file i.e. If the service is running, how do I set the TransitionDrawable to main_on in onResume()? I tried using the setDrawableByLayerId() method but it doesn't seem to be working. Not sure if I'm just not using it correctly though. Any help is appreciated. Thanks.


Solution

  • Never mind, found a solution.

    I put the following code in my onResume():-

    if(DRAWABLE_STATE==0) 
            TD_BG.resetTransition();
    else if(DRAWABLE_STATE==1) {
            TD_BG.resetTransition();
            TD_BG.startTransition(0);}
    

    In the above code, DRAWABLE_STATE is the flag that keeps track of whether the service is on or not. resetTransition() sets the TransitionDrawable to show the first layer, so when my service is off, it'll show main_off. If my service is on (i.e. DRAWABLE_STATE = 1) I just switch to layer one and then transition so fast (0ms) the user does not see a difference.