android - 在Android中,在OnClick中显示按下的按钮动画?

标签 android xml onclicklistener

我还没有找到关于如何在调用 onClick 时在按钮中制作动画的直接答案。我有一个像这样的 custom_btn.xml:

    <?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>

动画位于 btn_pressed.xml 中,如下所示:

    <?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>

我的问题是我似乎无法在这里找到正确的代码放入 onClickListener 中:

        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?

        } 
    });

谢谢!

最佳答案

来自 Android 文档: http://developer.android.com/guide/topics/resources/animation-resource.html

示例: XML 文件保存在 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>

此应用程序代码将动画设置为 View 的背景,然后播放动画:

ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image);
rocketImage.setBackgroundResource(R.drawable.rocket_thrust);

rocketAnimation = (AnimationDrawable) rocketImage.getBackground();
rocketAnimation.start();

关于android - 在Android中,在OnClick中显示按下的按钮动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11109227/

相关文章:

java - 您可以向 android XML 添加额外的字符串/整数变量吗?

android - 如何将项目添加到 android 选择的 TextView 上的弹出式复制/粘贴菜单中?

javascript - react native 不变违规 : View config

android - performClick() 和 callOnClick() 什么都不做

android - 在自定义 View 中注册到本地广播

xml - 我如何使用 cxml-stp 的 find-recursively 和 find-recursively-if

javascript - 为什么我的 Google 应用程序脚本出现系统标识符错误

Android - 单独类中的 OnClick 监听器

android - 为所有单选按钮添加事件监听器

javascript - 使用 Javascript 从本地文件夹读取 XML 文件