Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make fade out effect when view's background's state changed on Android?

Tags:

android

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?

like image 982
zzy Avatar asked Nov 13 '14 02:11

zzy


People also ask

How to set animation in Android?

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.


1 Answers

Try to define fade duration in drawable selector

<selector xmlns:android="http://schemas.android.com/apk/res/android"
          android:enterFadeDuration="150" android:exitFadeDuration="150">
like image 128
Stepango Avatar answered Oct 23 '22 05:10

Stepango