How to make the effect of fading when the background image on Android changes?

Now I have a button and use the selector as the background, the selector has pressed and focus state:

 <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@color/item_gray" /> <!-- pressed --> <item android:state_focused="true" android:drawable="@color/item_gray" /> <!-- focused --> </selector> 

And button code:

 <Button android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/button_selector" android:text="@string/hello_world" /> 

Using the button, you can change the background when its state has changed. And now I need the background to change more beautifully. Therefore, I want to add a fading effect between two changes in the background state.

I searched google and many documents and read Button source code, I found that I can do this if I Override the setPressed function .

I can find out the state changing in setPressed and draw an additional bitmap that will play the fading animation. But I think this is not a good ideal. So I came here to ask if there is a better way to achieve this?

+5
source share
1 answer

Try to determine the decay time in the selector

 <selector xmlns:android="http://schemas.android.com/apk/res/android" android:enterFadeDuration="150" android:exitFadeDuration="150"> 
+11
source

Source: https://habr.com/ru/post/1206765/


All Articles