Reputation: 55613
I've been googling for hours on this, SO seems to have a bunch of questions, some with accepted answers, but they don't make sense.
I have a ListView and I want that, onTouch, an item be highlighted, but if the user moves their finger and doesn't "complete" the touch (their finger is outside the view when it is lifted) then the highlight should go away.
If I try to consume the touches by having the following in my View
:
onTouch(View view, MotionEvent ev) {
....logic
//return false so this view keeps consuming the touches
return false;
}
The the touch never gets propagated to the ListView
and onItemClick
never gets called. I can hack my way through this by having my adapter be a listener to all of the views and pass "complete" touch events to the adapter, which will pass it back to the ListView
which can then pass it on to whoever, but this just seems ludicrous.
For the record, the highlight I'm trying to perform is a moderately complex highlight (involving changing the backgrounds of multiple, dynamic, subviews, so I can't just use a StateDrawable
...at least I don't think so, do StateDrawables
work on multiple subviews?
iOS handles this very simply in their UITableViewDelegate
, it seems crazy that this is so hard on android, I must be missing something. Any help is appreciated.
Upvotes: 3
Views: 1693
Reputation: 3562
Define a selector 'item_sel.xml' in res/drawable like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/my_highlight_color" android:state_pressed="true"/>
<item android:drawable="@color/my_default_color"/>
</selector>
where my_default_color
and my_highlight_color
are colors defined by you, for instance in res/values/colors.xml. Then set this selector as the background of your item view (not the ListView), that is:
android:background="@drawable/item_sel.xml"
You should be good to go from here.
Upvotes: 1