clicklistener and longclicklistener on the same button?

后端 未结 3 645
清歌不尽
清歌不尽 2021-01-15 02:38

i am creating a call/dial button, when i click on that call/dial button, a call will be made based on the input that is displayed in the edittext. I managed to do that part.

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-15 03:25

    A GestureDetector with a SimpleOnGestureListener would help you differentiate between the different types of presses. A GestureDectector is a class which can read different types of touch events (for example, single taps and long presses), and sends them to a listener which handles each type differently. Here's the documentation on the Detector and Listener.

    http://developer.android.com/reference/android/view/GestureDetector.html

    http://developer.android.com/reference/android/view/GestureDetector.SimpleOnGestureListener.html

    First, set up your SimpleOnGestureListener, the important methods for you to override will be onSingleTapUp and onLongPress. In your onCreate, create an instance of GestureDetector that references your listener. Then, attach an OnTouchListener to your button that sends the event to your detector. You'll want it to look something like this:

    //Set up the Detector
    GestureDetector.SimpleOnGestureListener myGestureListener = new GestureDetector.SimpleOnGestureListener()
    {
        @Override
        public boolean onSingleTapUp(MotionEvent e)
        {
            //Your onClick code
            return false;
        }
    
        @Override
        public void onLongPress(MotionEvent e)
        {
            //Your LongPress code
            super.onLongPress(e);  
        }
    };
    
    //And make a variable for your GestureDetector
    GestureDetector myGestureDetector;
    
    ...
    
    @Override
    onCreate(Bundle b)
    {
        ...
        myGestureDetector = new GestureDetector(myActivity.this, myGestureListener);
        ...
    }
    
    ...
    
    //And finally, wherever you are setting up your button
    button.setOnTouchListener(new View.OnTouchListener(){
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent)
        {
             myGestureDetector.onTouchEvent(motionEvent);
             return false;
        }
    

    There a a bunch of other types of events this class can interpret in case you want to get even more fancy. GestureDetector is a very good class to do a little research on, it can be very useful and isn't too complex. Hope this helps.

提交回复
热议问题