brian
brian

Reputation: 6912

Change row background color while item be touch in ListView

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?

Upvotes: 3

Views: 10014

Answers (3)

Abhishek Batra
Abhishek Batra

Reputation: 1599

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.

Upvotes: 2

dmon
dmon

Reputation: 30168

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.

Upvotes: 3

Rajdeep Dua
Rajdeep Dua

Reputation: 11230

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);

Upvotes: 1

Related Questions