Highlight Android in Touch Down in ListView
I've worked on this for many hours, 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, onTouch, the item to be highlighted, but if the user moves their finger and does not "complete" the touch (their finger goes out of bounds when released) then the highlight should go away.
If I try to use strokes while having the following in mine View
:
onTouch(View view, MotionEvent ev) {
....logic
//return false so this view keeps consuming the touches
return false;
}
The touch never extends to ListView
and onItemClick
will never be called. I can hack this by adding that my adapter is a listener for all views and passes "completed" touch events to the adapter, which passes it back to ListView
, which can then pass it on to anyone else, but that just seems ridiculous.
For the record, the highlighting I'm trying to accomplish is moderately complex highlighting (changing the backgrounds of multiple, dynamic, subzones, so I can't just use StateDrawable
... at least I don't think so, do StateDrawables
multiple subviews work?
iOS handles this very simply in its own UITableViewDelegate
, it seems crazy that it is so hard for android I must be missing something. Any help is appreciated.
source to share
- Use a selector on list items.
Define the "item_sel.xml" selector 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 the colors you defined, for example in res / values /colors.xml. Then set this selector as the background of your item (not ListView), namely:
android:background="@drawable/item_sel.xml"
You must be kind to walk from here.
source to share