Rob Rob - 3 months ago 23
Android Question

how to use both Ontouch and Onclick for an ImageButton?

in my app, i want two things to happen.


  1. when i touch and drag the ImageButton, it should move along with my finger.

    i used
    OnTouchListener()
    for this and it works fine.

  2. when i click the ImageButton, it should close the activity.

    i used
    OnClickListener()
    for this and it also works fine.



So, here is my problem. whenever i move the
ImageButton
OnTouchListener
is tirggered and the
ImageButton
moves, the
OnClickListener
is also triggered at the end when i am releasing the button from moving.

How to use ontouch and onclick listeners on the same button without interfering on each other?

Answer

Try this, It may help you

No need to set onClick() method onTouch() will handle both the case.

package com.example.demo;

import android.app.Activity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageButton;

public class MainActivity extends Activity {
    private GestureDetector gestureDetector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gestureDetector = new GestureDetector(this, new SingleTapConfirm());
        ImageButton imageButton = (ImageButton) findViewById(R.id.img);

        imageButton.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {

                if (gestureDetector.onTouchEvent(arg1)) {
                    // single tap
                    return true;
                } else {
                    // your code for move and drag
                }

                return false;
            }
        });

    }

    private class SingleTapConfirm extends SimpleOnGestureListener {

        @Override
        public boolean onSingleTapUp(MotionEvent event) {
            return true;
        }
    }

}
Comments