4

I basically want to customize list item`s background color while it is touched. I tired writing a listener but it seams that I made some kind of mistake or misunderstood the concept of these actions.

v.setOnTouchListener( new TextView.OnTouchListener() {

    public boolean onTouch(View v, MotionEvent event) {
            switch(event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                v.setBackgroundColor(Color.RED); 
                    break;
            case MotionEvent.ACTION_UP:
                v.setBackgroundColor(Color.WHITE);
                break;
            }

    return false;
    }
}
);

Default color is light blue. I want to change it for every list item. This code changes items color to red when touched but it does not change back after that.

PovilasID
  • 883
  • 10
  • 34

3 Answers3

5

But maybe the best would be to use color states...create a file mycolors.xml in the color folder with this:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_pressed="true"
              android:color="#ff0000"/> <!-- pressed -->
        <item android:color="#ffffff"/> <!-- default -->
    </selector>

then later you set the background of the view like this: android:background="@color/mycolors" in the layout xml or programmatically like this: v.setBackgroundColor(getResources().getColor(R.color.mycolors);

no clicks or touch listeners will be necessary in this case..everything will happen magically.

more about it: http://developer.android.com/guide/topics/resources/color-list-resource.html

Alécio Carvalho
  • 13,481
  • 5
  • 68
  • 74
1

Did you try to catch ACTION_CANCEL too?

So...

...
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
    v.setBackgroundColor(Color.WHITE);
     break;
...

I think the ListView is intecepting the touch event because it starts to scroll. So you never get an up-action but a cancel-action (I assume).

Knickedi
  • 8,742
  • 3
  • 43
  • 45
-1

use a statelistdrawable. you can find examples all over, including the Android developer site.

toadzky
  • 3,806
  • 1
  • 15
  • 26
  • The key point is that you can create a StateListDrawable programmaticaly with `StateListDrawable states = new StateListDrawable(); states.addState(new int[] {android.R.attr.state_pressed}, new ColorDrawable(color));` – Sylphe Jan 30 '14 at 10:32