【问题标题】:How to use drawable animation on button press如何在按钮按下时使用可绘制动画
【发布时间】:2026-01-06 20:45:02
【问题描述】:

我在这里尝试了很多代码,但没有任何效果 并且根本没有教程如何使用 按下按钮时可绘制动画。

但是没有起作用了。

我试过了:

<?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/pressed" />
    <item android:state_pressed="false" android:drawable="@drawable/lostpressd" />
</selector>

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/e1" android:duration="50" />
    <item android:drawable="@drawable/e2" android:duration="50" />
    and so on 

和lostpress相反。

【问题讨论】:

  • 你到底想要什么?按下按钮的点击效果?
  • 正如标题所说,当按下按钮时,应该播放按钮可绘制动画。

标签: android android-animation android-button


【解决方案1】:

我解决了你的问题:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/image1" android:state_pressed="true" />
    <item android:drawable="@drawable/image2" android:state_pressed="false" />
</selector>

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
    android:oneshot="false">
    <item
        android:drawable="@drawable/image1"
        android:duration="200" />
    <item
        android:drawable="@drawable/image2"
        android:duration="200" />
    <item
        android:drawable="@drawable/image3"
        android:duration="200" />
</animation-list>

在你的活动中:

 final ImageView img = (ImageView) findViewById(R.id.my_img);
    img.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            img.setBackgroundResource(R.drawable.anim);
            AnimationDrawable animationDrawable = (AnimationDrawable) img.getBackground();
            animationDrawable.setVisible(true, true);
            animationDrawable.start();

        }
    });

【讨论】:

  • 您好,感谢您的尝试。但我不使用 ImageView。在一个按钮上,我得到 android.graphics.drawable.StateListDrawable 不能转换为 android.graphics.drawable.AnimationDrawable
【解决方案2】:

首先,创建一个动画矢量drawable。这是一个非常好的(简单)教程:https://medium.com/@naththeprince/delightful-animations-in-android-d6e9c62a23d3。接下来,在您的 xml 文件中,定义一个普通按钮,如下所示:

<Button
  android:drawableLeft="@drawable/your_animated_vector_drawable"
  android:id="@+id/example_button"/>

并在Button 中添加您想要的任何其他属性。

在你的代码中,使用这个:

Button button = (Button) findViewById(R.id.example_button);
button.setOnClickListener(v -> {
  // Get the left drawable: (the one you set in the xml file)
  AnimatedVectorDrawable avd =
    (AnimatedVectorDrawable) showPopup.getCompoundDrawables()[0];
  avd.start();
});

这对我有用。希望它也适用于您!

【讨论】:

    最近更新 更多