2012-06-19 77 views
2

我還沒有找到直接的答案,如何在調用onClick時在按鈕中製作動畫。我有一個custom_btn.xml像這樣:在Android中,在OnClick中顯示按下的按鈕動畫?

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

     } 
    }); 

謝謝!

回答

2

從Android文檔: http://developer.android.com/guide/topics/resources/animation-resource.html

例如:

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

此應用程序代碼將設置動畫爲背景的景觀:在保存RES /動畫/ rocket.xml XML文件,然後播放動畫:

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

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

謝謝Udinic。你給的鏈接是有幫助的。結果我需要做的只是將android:oneshot =「true」添加到btn_pressed.xml中 – kirktoon1882

相關問題