0

I have a custom selector for my ListView items. This is what it looks like:

<item android:drawable="@color/transparent" android:state_activated="false"/>
<item android:drawable="@color/blue" android:state_activated="true"/>

When I tap on an item, it's background turns blue. I want to do this "tapping" via code but I don't know what method to call even if I already know the child's position in ListView.


Actually, what I really want is to change the background of a row (similar to when it is tapped) without firing onListItemClick().

user1923613
  • 626
  • 5
  • 11
  • 31

3 Answers3

2

I want to do this "tapping" via code

Fetch the row that you want (it must be on the screen) and call performClick() or maybe you can use setActivated(true) (I've never tried this method.)

A--C
  • 36,351
  • 10
  • 106
  • 92
Sam
  • 86,580
  • 20
  • 181
  • 179
  • But performclick() doesn't take the row position as a parameter. I've tried performItemClick() but I just calls my onListItemClickListener without changing the background. I've also tried setActivated(true) but still no effect. – user1923613 Mar 08 '13 at 20:53
  • Try `listView.setItemChecked(position, true);` – Sam Mar 08 '13 at 21:02
0

What if you tried emulating a touch event? Perhaps not the cleanest answer, but...

Get your desired row's view then call

rowView.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 0, 0, 0));
dennisdrew
  • 4,399
  • 1
  • 25
  • 25
0

Change your selector to toggle on android:state_selected="true", then use listView.setSelection(index);

Andrew Cranston
  • 396
  • 3
  • 3