Search code examples
androidonclickonclicklistenertouch-eventontouch

Android onTouch() makes sound like double tap


I've implemented onTouch for my layout to function as buttons.
It all works great besides the fact that a 2 clicks sound is made sometimes as touching the button.
I've tried to debug it but I wasn't able to understand what is the problem.

Here is the onTouch code :

button.setOnTouchListener(new OnTouchListener() 
{
    @Override
    public boolean onTouch(View v, MotionEvent event)
    {
        Log.d(TAG, "onTouch "+event.getAction());
        switch (event.getAction())
        {
            case MotionEvent.ACTION_HOVER_ENTER:
                v.setBackgroundResource(R.color.main_menu_buttons_bg_pressed);
                break;
            case MotionEvent.ACTION_HOVER_EXIT:
                v.setBackgroundResource(R.color.background_color);
                break;
            case MotionEvent.ACTION_DOWN:
                v.setBackgroundResource(R.color.main_menu_buttons_bg_pressed);
                break;
            case MotionEvent.ACTION_UP:
                Log.d(TAG, "on click");
                v.performClick();
                v.setBackgroundResource(R.color.background_color);
                break;
            default:
                // empty    
        }
        return false;
    }
});

As you can see I've added log messages, which usually prints :

onTouch 0
onTouch 2
onTouch 2
onTouch 2
onTouch 2
onTouch 1
on click

so it should be ok but yet the clicks are heard twice (sometimes, can't determine exactly when it happens)


Solution

  • it's the expected behaviour du of v.performClick(); , when the view has also an OnClikListener: From GrepCode

    2480    public boolean More ...performClick() {
    2481        sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
    2482
    2483        if (mOnClickListener != null) {
    2484            playSoundEffect(SoundEffectConstants.CLICK);
    2485            mOnClickListener.onClick(this);
    2486            return true;
    2487        }
    2488
    2489        return false;
    2490    }