Search code examples
androidmotionevent

MotionEvent ACTION UP Unable to detect long press


I'm having some issues with MotionEvent. I want to show background changes when user presses the button (but not released yet), so OnClick might not be able to help. I noticed MotionEvent is able to detect pressed and released.

As result I have implemented a simple onTouch event as shown below:

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_DOWN) {
                // Make Background Changes

                Log.i("DOWN", String.valueOf(getAdapterPosition()));
                sparseBooleanArray.put(getAdapterPosition(), true);
                notifyItemChanged(getAdapterPosition());

            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                // Revert background to normal

                Log.i("UP", String.valueOf(getAdapterPosition()));
                sparseBooleanArray.put(getAdapterPosition(), false);
                notifyItemChanged(getAdapterPosition());
            }
            return false;
        }

This means when I press -> Background becomes green

And when I release -> Reverts back to original (white).

It works well on normal click, but when try long press, DOWN is being called, but when release UP is not being called.

So I need to perform normal click again to get the background back to normal.

Is it the original design, and I need to utilize OnLongClickedListener and manually revert back to normal when released.

Thank You.


Solution

  • It will be easier to use a state list as the background of your item, using the pressed state. See https://developer.android.com/guide/topics/resources/drawable-resource#StateList

    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:state_pressed="true"
               android:drawable="@color/colorGreen" />
        <!-- This is the default state item, at the end of the list -->
        <item android:state_pressed="false"
               android:drawable="@color/colorWhite" />
    </selector>