How to use View.OnTouchListener instead of onClick

VansFannel picture VansFannel · Jul 27, 2012 · Viewed 140.6k times · Source

I'm developing an Android 2.2.2 application for a client and he wants to do the following:

Now I have a button with an onClick event but he doesn't like, he wants to dectect when user release the button.

I've found View.OnTouchListener which I think this is what I need to use but, is there any posibility to add this event to xml like I did with onClick?

<ImageButton
    android:id="@+id/btnSaveNewGate"
    android:layout_width="@dimen/btnSaveNewGate_width"
    android:layout_height="@dimen/btnSaveNewGate_height"
    android:layout_below="@+id/radioGrGateType"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="@dimen/btnSaveNewGate_marginTop"
    android:background="@null"
    android:contentDescription="@string/layout_empty"
    android:onClick="onSaveNewGateClick"
    android:scaleType="fitXY"
    android:src="@drawable/save_gate_selector" />

I have two questions more:

Which is the event associated when user releases his finger?

Is there any guidelines which prohibit using View.OnTouchListener instead of onClick?

Answer

Andy Res picture Andy Res · Jul 27, 2012

The event when user releases his finger is MotionEvent.ACTION_UP. I'm not aware if there are any guidelines which prohibit using View.OnTouchListener instead of onClick(), most probably it depends of situation.

Here's a sample code:

imageButton.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction() == MotionEvent.ACTION_UP){

            // Do what you want
            return true;
        }
        return false;
    }
});