views:

86

answers:

1

I have two drawables that are used as backgrounds to indicate state (pressed or selected) of my list items. The Pressed drawable is a selector, but with no state specified; it is wired up via XML to be the android:listSelector for the list.

<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android"&gt;
    <item
        android:drawable="@drawable/my_actual_drawable" />
</selector>

The Selected drawable, however, is applied by code, because it's complicated and more than one simple background drawable change needs to happen when an item is selected.

If I click very quickly between two list items, one item can have (and keep) the Selected highlight while a different item has (and keeps) the Pressed highlight. I believe this is because the press happens so quickly that it is not interpreted by the underlying framework as a click, so no onItemClick reaches my list.

One solution is to use the selector with state (that's what selectors are for!):

<?xml version="1.0" encoding="utf-8"?>
<selector
    xmlns:android="http://schemas.android.com/apk/res/android"&gt;
    <item android:state_pressed="true"
        android:drawable="@drawable/my_actual_drawable" />
</selector>

but this has the unfortunate effect of turning off the Pressed highlight before my code can apply the Selected highlight, so there is a flash of unhighlightedness between the two states, no matter how early in the onItemClick handler I put the setBackgroundResource call.

Another solution would be to monitor not only onItemClick events, but also onTouch events, and handle everything in code; that appears to make things too slow.

What can I do to avoid both the flash and the double-selection state?

+1  A: 

I see where you say that your situation is more complex than just simply changing the background drawable, so I'm sorry if I have over-simplified.

Why don't you let the xml selector handle all that it can? You should be able to setup the selector xml to handle both the pressed and selected states for changing the background resource to avoid the flash and double-selection that you're seeing. My assumption is that the other stuff that you're doing in java is fast enough to not be noticeable if the background isn't doing strange things.

I like to use the list_selector_background from the android framework and the drawable documentation for state list as my references for doing things like this although the list_selector_background is probably a little more complex that yours will need to be.

John
Thanks; this makes sense. I will try it out and let you know how it works.
Carl Manaster