Search code examples
javaandroidlistviewmotioneventontouch

ListView onTouch MotionEvent


I have a list ListView. Wrote a handler for it touches. When you touch the menu item (ACTION_DOWN) I'm highlighting it. When you release the item (ACTION_UP) - returns the original color. The problem is that if you touch and scroll - and then the item is highlighted. Or if you touch and move your finger on the other item.

public boolean onTouch(View v, MotionEvent event) {
if (event.getAction()==MotionEvent.ACTION_DOWN) {
    holder.tv_name_exercise.setTextColor(Color.parseColor("#fe9503"));
    holder.tv_description_exercise.setTextColor(Color.parseColor("#ffffff"));
    holder.row.setBackgroundResource(R.drawable.list_item_bg_active);
    }
if (event.getAction()==MotionEvent.ACTION_UP) {
    holder.tv_name_exercise.setTextColor(Color.parseColor("#000000"));
    holder.tv_description_exercise.setTextColor(Color.parseColor("#666667"));
    holder.row.setBackgroundResource(R.drawable.list_item_bg);
    }}

Solution

  • Instead of using a touch handler, set your text views to use color state lists for the text color and set your background resource to be a selector drawable. The framework will handle picking the correct resources based on your view's current state (e.g. pressed).

    res/color/exercise_color.xml:

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_pressed="true" android:color="#fe9503" />
        <item android:color="#000000"/>
    </selector>
    

    res/drawable/row_bg.xml:

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_pressed="true"
              android:drawable="@drawable/list_item_bg_active" />
        <item android:color="@drawable/list_item_bg"/>
    </selector>