In Android, Display pressed button animation in OnClick?
12,495
From the Android documentation: http://developer.android.com/guide/topics/resources/animation-resource.html
example: XML file saved at res/anim/rocket.xml:
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item android:drawable="@drawable/rocket_thrust1" android:duration="200" />
<item android:drawable="@drawable/rocket_thrust2" android:duration="200" />
<item android:drawable="@drawable/rocket_thrust3" android:duration="200" />
</animation-list>
This application code will set the animation as the background for a View, then play the animation:
ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image);
rocketImage.setBackgroundResource(R.drawable.rocket_thrust);
rocketAnimation = (AnimationDrawable) rocketImage.getBackground();
rocketAnimation.start();
Author by
kirktoon1882
Updated on June 15, 2022Comments
-
kirktoon1882 almost 2 years
I haven't found a straight answer to how to make an animation in a button when onClick is called. I've got a custom_btn.xml like so:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/btn_pressed"></item> <item android:state_focused="true" android:drawable="@drawable/btn_on"></item> <item android:drawable="@drawable/btn"></item> </selector>
and the animation is in btn_pressed.xml like so:
<?xml version="1.0" encoding="utf-8"?> <animation-list xmlns:android="http://schemas.android.com/apk/res/android" > <item android:drawable="@drawable/btn_on_1" android:duration="30" /> <item android:drawable="@drawable/btn_on_2" android:duration="30" /> <item android:drawable="@drawable/btn_on_3" android:duration="30" /> <item android:drawable="@drawable/btn_on_4" android:duration="30" /> <item android:drawable="@drawable/btn_on_5" android:duration="30" /> </animation-list>
my problem is that I can't seem to find the right code to go in the onClickListener here:
button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //-- what is the proper animation call that would go here to make btn_pressed.xml cycle only once when pressed? } });
thanks!
-
kirktoon1882 almost 12 yearsThanks Udinic. The link you gave was helpful. Turns out all I needed to do was add android:oneshot="true" to the btn_pressed.xml