Changing the background color of a row when an item touches a ListView

I am trying to use BaseAdapter to display an item in a ListView. I am trying to make the code below 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 the item will be affected, it changes the background to ic_corner_four_click. But until you release your finger or move on to another item, it has not changed to ic_corner_four. How to change it?

+3
source share
3 answers

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

This, for example,.

+3
source

You need to set the selection mode as a list

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

 listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); 
+1
source

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

+1
source

Source: https://habr.com/ru/post/1437904/


All Articles