Android TransitionDrawable with multiple items
android, java
Solution
You can do it by using a handler
mAnimateImage is your button
int DrawableImage[] = {R.drawable.back_red, R.drawable.back_green, R.drawable.back_purple};
final Handler handler = new Handler();
final int[] i = {0};
final int[] j = {1};
handler.postDelayed(new Runnable() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
Resources res = getApplicationContext().getResources();
TransitionDrawable out = new TransitionDrawable(new Drawable[]{res.getDrawable(DrawableImage[i[0]]), res.getDrawable(DrawableImage[j[0]])});
out.setCrossFadeEnabled(true);
mAnimateImage.setBackgroundDrawable(out);
out.startTransition(4000);
i[0]++;
j[0]++;
if (j[0] == DrawableImage.length) {
j[0] = 0;
}
if (i[0] == DrawableImage.length) {
i[0] = 0;
}
handler.postDelayed(this, 8000);
}
});
}
}, 0);
Problem
I want to create a Button in Android with a text, and a background image. The background image should crossfade every X time. I have this working using a TransitionDrawable with 2 images. But I can't get this to work with more than 2 images. What I have : In Java code I create a Button and set a background (which is a TransitionDrawable defined in XML). And I start the transition. ``` final Button b = new Button(getApplicationContext()); b.setTextColor(getResources().getColor(R.color.white)); b.setText("Some text"); b.setBackgroundDrawable(getResources().getDrawable(R.drawable.tile)); StateListDrawable background = (StateListDrawable) b.getBackground(); TransitionDrawable td = (TransitionDrawable) background.getCurrent(); td.startTransition(2000); ``` In XML I define in tile.xml ``` <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" > <shape> <solid android:color="#449def" /> </shape> </item> <item android:drawable="@drawable/transition"> <shape> <solid android:color="#0000ff" /> </shape> </item> </selector> ``` And finally a transition.xml ``` <?xml version="1.0" encoding="utf-8"?> <transition xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false"> <item android:drawable="@drawable/desert"/> <item android:drawable="@drawable/hydrangeas" /> <item android:drawable="@drawable/jellyfish" /> </transition> ``` Now the effect is that when I start the app the desert image is shown. This image crossfades to the hydrangeas image as it should. But the jellyfish image is never shown. In the doc for TransitionDrawables it is stated that you can specify more than 2 drawables but I can't get this to work. I also tried this without any XML but in pure JAVA but this gave exactly the same problem :-(