How can I create animated ToggleButton?

拜拜、爱过 提交于 2019-12-24 00:01:13

问题


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:


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();


来源:https://stackoverflow.com/questions/19008555/how-can-i-create-animated-togglebutton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!