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

时间:2012-06-19 20:50:59

标签: 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?

        } 
    });

谢谢!

1 个答案:

答案 0 :(得分:2)

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

例如: 保存在res / anim / rocket.xml的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>

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

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

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