How can I create animated ToggleButton?

2019-07-19 06:54发布

Yes, I can create ToggleButton with 2 pictures(On, Off) But I want to create a ToggleButton with 3-5 pictures.

For example, when is it OFF and I click:

  1. Off picture
  2. Middle picture
  3. On picture

And when is it ON and I click:

  1. On picture
  2. Middle picture
  3. OFF picture

So it is like frame animation, that I can use with duration with ImageView.

1条回答
贪生不怕死
2楼-- · 2019-07-19 07:08

EDIT:

You can use Frame Animation: In res/drawable/myanim.xml:

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/pic_one" android:duration="50"/>
    <item android:drawable="@drawable/pic_two" android:duration="50" />
    <item android:drawable="@drawable/pic_three" android:duration="50" />
</animation-list>

You can then use this animation as a plain drawable:

<ImageView android:id="@+id/image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/myanim"/>

To start the animation you do

AnimationDrawable backgroundDrawable = (AnimationDrawable) image.getDrawable();
backgroundDrawable.start();

You can also use a Value Animator. I haven't tested this, but you should be able to put something like this into onClick handler of you button:

int[] backgrounds = ...;//ids of the backgrounds for the button
ValueAnimator anim = ValueAnimator.ofInt(0, backgrounds.length);
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        int i = (Integer) animation.getAnimatedValue();
        int backgroundId = backgrounds[i];
        yourButton.setBackgroundResource(backgroundId);
    }
});
anim.setDuration(500); //0.5 seconds
anim.start();
查看更多
登录 后发表回答