Android selector. How to go to normal state after press?

2.7k views Asked by At

I've got a list of cards, and when the user presses on them, it goes to different fragments.

I'm using a selector on a card to have a "pressed state". I use the following XML:

<selector xmlns:android="http://schemas.android.com/apk/res/android" >

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

    <item
        android:state_enabled="true"
        android:state_focused="true"
        android:drawable="@color/transparent" />

    <item
        android:drawable="@color/transparent" />

</selector>

When I press on a card, if the next fragment takes 1 second to load, the card stays in the "pressed" state, until the fragment is displayed. Does someone know how to do like in recent Google apps (Messenger, Gmail, ...), ie after the press, the card goes to "normal" state, and then after the fragment is ready, the fragment is displayed.

Thanks.

UPDATE: The problem doesn't seem to be in the selector. If instead of going to another fragment I go to display another activity, the card goes to normal state. It's only when going to a fragment. It's like if the fragment takes all the resources and prevent the normal state to be displayed.

Yet, if we go to the onTouchEvent() method of the View class, there's this code:

// Use a Runnable and post this rather than calling
// performClick directly. This lets other visual state
// of the view update before click actions start.
if (mPerformClick == null) {
  mPerformClick = new PerformClick();
}
if (!post(mPerformClick)) {
  performClick();
}

So I don't know why the normal state is not displayed...

2

There are 2 answers

0
SilentKiller On

Try with the following Selector for CardView

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
          android:drawable="@drawable/card_on_press"/>
    <item android:state_focused="true" android:state_enabled="true"
          android:drawable="@drawable/card_on_focus"/>
    <item android:state_enabled="true"
          android:drawable="@drawable/card_default"/>
    <item android:state_enabled="false"
          android:drawable="@drawable/card_on_press"/>
</selector>

Note: Drawable default will be fine as a transparent item as CardView provides a default background for all android versions

0
iMDroid On

Try this...

<selector xmlns:android="http://schemas.android.com/apk/res/android" >

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

<item
    android:drawable="@color/transparent" />