androidanimationtransitiondrawable

Crossfading using TransitionDrawable not working on android


I have two Images that I want to cross fade. Initially they both use imageview. I then use .getDrawable() to get the drawable of the images.

This is the code I used

Drawable backgrounds[] = new Drawable[2];
backgrounds[0] = BackgroundImage.getDrawable();
backgrounds[1] = BackgroundImageBlurred.getDrawable();

TransitionDrawable crossfader = new TransitionDrawable(backgrounds);
crossfader.startTransition(3000);

It only shows the image on the first array element, which it shows anyway since both images were set to visible in the XML.

The transition doesn't start

Any help would be appreciated :)


Solution

  • Here's an example IF you have 2 drawables and want to animate their transition in some ImageView:

    package com.example.app;
    
    import android.app.Activity;
    import android.content.res.Resources;
    import android.graphics.drawable.Drawable;
    import android.graphics.drawable.TransitionDrawable;
    import android.os.Bundle;
    import android.widget.ImageView;
    
     class MainActivity extends Activity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            Drawable backgrounds[] = new Drawable[2];
            Resources res = getResources();
            backgrounds[0] = res.getDrawable(android.R.drawable.btn_star_big_on);
            backgrounds[1] = res.getDrawable(android.R.drawable.btn_star_big_off);
    
            TransitionDrawable crossfader = new TransitionDrawable(backgrounds);
    
            ImageView image = (ImageView)findViewById(R.id.image);
            image.setImageDrawable(crossfader);
    
            crossfader.startTransition(3000);
    
        }
    }
    

    Then if you want to transition back to the original image you can call

    // Make sure the transition occurred
    crossfader.startTransition(0);
    // Reverse transition
    crossfader.reverseTransition(3000);
    

    Please correct me if I misunderstood your question.