-1

I have a custom listview in my android application. When a user press an item in the list I want to change the background color of the pressed item. This is the code for that behaviour:

tempView.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View arg0, MotionEvent event) {

                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    isDown = false;
                    tempView.setBackgroundColor(Color.parseColor("#f47920"));

                }

                if (event.getAction() == MotionEvent.ACTION_UP) {
                    tempView.setBackgroundResource(R.drawable.list_selector_focused);
                }

                if(event.getAction() == MotionEvent.ACTION_MOVE) {
                    tempView.setBackgroundResource(R.drawable.list_selector_focused);
                }


                return false;
            }
        }); 

But when I "Fling" my finger over the screen to scroll the listview, an item is also marked, and the "pressed" color will be static. How can I avoid this?

Tobias Moe Thorstensen
  • 8,861
  • 16
  • 75
  • 143
  • 1
    why don't you try using a `selector` on your ListView. Have you seen this:http://stackoverflow.com/questions/4247385/how-to-change-color-of-listview-items-on-focus-and-on-click ? – Parth Doshi Oct 24 '12 at 11:52
  • Yes, sure I have. But there has to be a way to do this in java as well? – Tobias Moe Thorstensen Oct 24 '12 at 11:54
  • You want to change the background while they are holding down finger, or when they have done the click? – Carnal Oct 24 '12 at 11:58
  • By 'fling' you mean drag? What do you mean by '"pressed" color' ? Do you really want to take care about the view's color yourself instead of letting the view do it itself by defining a XML selector for it? Or for the listitem itself? Also, if you want the selected items to change color, think about writing your own ArrayAdapter which will change colors of the pressed item in it's getView() method. – Shark Oct 24 '12 at 11:59
  • 1
    yeah your right! but since Android gives us the option to create a `StateListDrawable` I would prefer the XML and I feel using `setBackgroundResource` every time isn't a good idea! – Parth Doshi Oct 24 '12 at 12:00

1 Answers1

1

MotionEvent.ACTION_UP will not be caught unless you return true from onTouch() to inform Android system that you handled the whole touch event.

Mohamed_AbdAllah
  • 5,311
  • 3
  • 28
  • 47
  • Thanks for the heads up, but an item will still be marked with the "pressed color" if I fling my finger to scroll the listview. – Tobias Moe Thorstensen Oct 24 '12 at 11:48
  • My guess is that since ACTION_UP is not set, the `tempView.setBackgroundResource(R.drawable.list_selector_focused);` will not be executed, so the color remains unchanged. – Mohamed_AbdAllah Oct 24 '12 at 12:05