3

I try to use BaseAdapter to show item in ListView. I try below code in BaseAdapter.

@Override
    public View getView(final int position, View convertView, ViewGroup parent) {
    //...
    convertView.setOnTouchListener(new OnTouchListener() {
@Override
    public boolean onTouch(View v, MotionEvent event) {
       switch(event.getAction()) {
         case MotionEvent.ACTION_DOWN:
         v.setBackgroundResource(R.drawable.ic_corner_four_click);
     break;

         case MotionEvent.ACTION_UP:
         v.setBackgroundResource(R.drawable.ic_corner_four);
     break;
     }

     return false;
     }
   });
}

While item be touched, it change background to ic_corner_four_click. But while release finger or move to other item, it did not rechange to ic_corner_four. How to modify it?

NagarjunaReddy
  • 8,621
  • 10
  • 63
  • 98
brian
  • 6,802
  • 29
  • 83
  • 124

3 Answers3

3

You should use a StateListDrawable to define the background in a specific state. See the documentation. If you look to the right of the question you can see other very similar questions. --->

This one, for example.

Community
  • 1
  • 1
dmon
  • 30,048
  • 8
  • 87
  • 96
  • iam using stateListDRawable. but when we scroll the list the selection goes off. why? how to fix that? i did lot searching and i tried "choice_mode_single" but i couldn't retain the highlight. any idea? – AD14 Feb 02 '12 at 04:49
  • Ah, that's a different problem. I thought you just wanted a particular background on touch. If you want to do that it's a bit more complicated. You have to keep the selection position in a model and override the getView() method in the adapter to call `view.setSelected(true)` if the view is the selected one. – dmon Feb 02 '12 at 14:19
2

The reason behind this problem is your onTouch function is always returning false. For ACTION_DOWN the code is executed and the function returns false. Now it is never called for ACTION_UP. Change return value to true should solve your problem.

Abhishek Batra
  • 1,539
  • 1
  • 18
  • 45
1

You need to set the select mode in the list view

http://developer.android.com/reference/android/widget/AbsListView.html#CHOICE_MODE_SINGLE

listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
Rajdeep Dua
  • 11,190
  • 2
  • 32
  • 22