Android:如何为自定义按钮添加彩色淡入动画

Kev*_* Li 0 animation android transition button

我已经为一个按钮指定了2个状态(按下和未按下状态).按下的按钮有一个填充的颜色,而未按下的按钮有一个带有一些文本的边框.当用户触摸时,如何使未按下的按钮淡入按下的按钮,并在用户松开按钮后立即恢复到未按下的按钮?

编辑:

似乎大多数答案并没有完全解决我的问题,虽然transitiondrawable似乎可以工作,但我不知道如何用我当前的代码实现它.

为了进一步说明,以下是我的代码,用于存储在名为button.xml的drawable文件夹中的按钮

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:drawable="@drawable/buttonpressed"
        android:state_enabled="true"
        android:state_pressed="true"/>

    <item
        android:drawable="@drawable/buttonnormal"
        android:state_enabled="true"/>

</selector>
Run Code Online (Sandbox Code Playgroud)

我已经在我的主xml文件中引用了drawable xml.

我希望能够在按下按钮时从"按钮正常"淡入"按下按钮",并在按钮被释放时恢复为"按钮正常".

小智 5

使用ObjectAnimator

int colorFrom = 0xaaaaaaaa;
int colorTo = 0xffFFFFFF;
int duration = 500;
Button myButton = (Button)findViewById(R.id.myButton);
ObjectAnimator anim = ObjectAnimator.ofObject(myButton, "backgroundColor", new ArgbEvaluator(), colorFrom, colorTo)

anim.addListener(new AnimatorListener() {
    @Override 
    public void onAnimationEnd(Animator animation) {
        // Trigger the events after animation is ended
    }
   @Override
    public void onAnimationEnd(Animation arg0) {
    }
    @Override
    public void onAnimationRepeat(Animation animation) {
    }
});
anim.setDuration(duration).start();
Run Code Online (Sandbox Code Playgroud)