Now I have a button and use selector as its background, the selector have 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 the button's code:
<Button
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/button_selector"
android:text="@string/hello_world" />
It is simple to let button change its background when its state changed. And now I need the background changing more beautiful. So I want add fade out effection between two background state's changing.
I searched the google and many documents and read the source code of Button, I found I can do it if I Override the setPressed function
.
I can know the state's changing in setPressed
and draw an additional bitmap which will play fade out animation. But I think this isn't a good ideal. So I came here to ask if there is any better way to reach it?
Navigate to the app > res > Right-Click on res >> New >> Directory >> Name your directory as “anim”. Inside this directory, we will create our animations. For creating a new anim right click on the anim directory >> Animation Resource file and give the name to your file.
Try to define fade duration in drawable selector
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:enterFadeDuration="150" android:exitFadeDuration="150">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With