24k_magic
24k_magic

Reputation: 31

Android UI - How to change images dynamically when using TransitionDrawable

I want to make a transition of some images using TransitionDrawable. However, TransitionDrawable only allows two images. How can I change the images dynamically?

Upvotes: 3

Views: 113

Answers (1)

0xCursor
0xCursor

Reputation: 2268

If you want to transition through more than two images with TransitionDrawable, you can do something like the following.

This is a test program I made as an example:

public class MainActivity extends AppCompatActivity {
    private ImageView image;
    private TransitionDrawable trans;
    private Resources res;
    private int images[] = {R.drawable.yourImage1, R.drawable.yourImage2, R.drawable.yourImage3};
    private int imageIndex1;
    private int imageIndex2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ConstraintLayout layout = new ConstraintLayout(this);
        setContentView(layout);

        imageIndex1 = 0;
        imageIndex2 = 1;

        image = new ImageView(this);
        image.setImageResource(images[0]);
        layout.addView(image);

        res = this.getResources();

        image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                trans = new TransitionDrawable(new Drawable[]{res.getDrawable(images[imageIndex1]), res.getDrawable(images[imageIndex2])});
                if (imageIndex1 == images.length-1) {
                    imageIndex1 = 0;
                } else {
                    imageIndex1++;
                }
                if (imageIndex2 == images.length-1) {
                    imageIndex2 = 0;
                } else {
                    imageIndex2++;
                }

                image.setImageDrawable(trans);

                // Set the parameter value to whatever time you want
                trans.reverseTransition(2000);
            }
        });
    }
}

I hope this is something similar to what you're looking for.

Upvotes: 0

Related Questions