动画仅在第一次按钮点击时起作用

3
我想知道如何正确处理动画。以下代码运行良好,但动画仅在第一次单击后开始。之后再次单击无效。
布局:
<Button
    android:id="@+id/play"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:background="@drawable/speaker" />

动画文件 'anim.xml':

<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="true" >
<item
android:drawable="@drawable/choose12"
android:duration="100"/>
<item
android:drawable="@drawable/choose12_1"
android:duration="100"/>
<item
android:drawable="@drawable/choose12_2"
android:duration="100"/>
<item
android:drawable="@drawable/choose12"
android:duration="100"/>
</animation-list>

活动:

final Button speakButton = (Button)findViewById(R.id.play);
    speakButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            String words = getResources().getString(R.string.select_age);
            speakWords(words);
            speakButton.setBackgroundResource(R.drawable.anim.xml);
            AnimationDrawable AppNameAnimation = (AnimationDrawable) speakButton.getBackground();
            AppNameAnimation.start();
        }
    });

在上面的代码中,动画仅在第一次单击时正常工作,但不会在第二次(或第三次,或第N次)单击时启动。
如何在每次单击按钮时都开始动画?
2个回答

2

我有过类似的问题。

如果我已经播放了动画,我会先调用停止动画,然后再解决问题。

           mAnimationDrawable.stop();
           mImageView.setImageDrawable(mAnimationDrawable);
           mAnimationDrawable.start();

1
尝试以下方式...也许是因为您已经将BackgroundResource设置为R.drawable.anim.xml。所以编译器无法再次编译这行代码。我认为AnimationDrawable不会为相同的资源启动。如果您动态更改它,就可以得到它。
final Button speakButton = (Button)findViewById(R.id.play);
    speakButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            String words = getResources().getString(R.string.select_age);
            speakWords(words);
            speakButton.setBackgroundResource(R.drawable.anim.xml);
            AnimationDrawable AppNameAnimation = (AnimationDrawable) speakButton.getBackground();
            AppNameAnimation.start();

            speakButton.post(new Runnable() {

               @Override
               public void run() {

                  if(AppNameAnimation.getCurrent() != AppNameAnimation.getFrame(AppNameAnimation.getNumberOfFrames() - 1))
                  {
                     speakButton.post(this);
                  }else
                  {
                     speakButton.removeCallbacks(this);
                     speakButton.setBackgroundResource(R.drawable.speaker);
                  }

               }
            });
        }
    });

1
嗨Gunaselan,你的代码在我的应用程序中非常非常好用。再次感谢你。 - user1731690

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接