Changing Images During Android Animation
I have been working on learning animations in Android, and, based on the tutorials, it's fairly easy so far. However, I wanted to take the animations a step further than what the tutorials teach.
I wanted to simulate the rolling of a die. Here is my code to add the die to the view.
<ImageButton android:id="@+id/dice" android:clickable="true"
android:onClick="rollDie" android:src="@drawable/dice_sides"
android:layout_alignParentRight="true" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:background="@null" />
The source, dice_sides
, is a level-list.
Adding the initial animation was easy. Within the rollDie
method in the Activity, I did this:
/**
* Roll of the die.
*
* @param view
* The view that is being acted upon.
*/
public void rollDie(View view) {
// Setup the animation.
Animation move = AnimationUtils.loadAnimation(view.getContext(),
R.anim.move);
View dice = findViewById(R.id.dice);
dice.setAnimation(move);
move.start();
}
That works fine. T开发者_JAVA百科he die image shakes back and forth.
What I want to have happen is the die to then display various numbers as it moves through the animation, until it stops on the last part of the animation. Unfortunately, I can't find much on how to do a second animation along with the first. Someone mentioned the use of handlers, but I don't quite understand how to use them in this situation. If anybody could point me in the right direction, I would appreciate it.
(For the record, here is dice_sides.)
<level-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:maxLevel="0" android:drawable="@drawable/die.1" />
<item android:maxLevel="1" android:drawable="@drawable/die.2" />
<item android:maxLevel="2" android:drawable="@drawable/die.3" />
<item android:maxLevel="3" android:drawable="@drawable/die.4" />
<item android:maxLevel="4" android:drawable="@drawable/die.5" />
<item android:maxLevel="5" android:drawable="@drawable/die.6" />
</level-list>
It took me a little bit to figure it out, but I finally determined how to get both parts of the animation working together. (The tip on handlers was spot on.) I wrote a blog post discussing how to get this to work. It can easily be extrapolated to more advanced animations.
精彩评论