Search code examples
javaandroidontouchlistener

Im not Getting the Button Release Toast in OnTouchListners


The issue is im not getting the Button release Toast. i've a simple view in xml on which im performing onTouch.

hidenBtn.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    int action = event.getActionMasked();
                    if (action == MotionEvent.ACTION_DOWN) {
                        firstTime=System.currentTimeMillis();
                        Toast.makeText(MainActivity.this, "Pressed", Toast.LENGTH_SHORT).show();
    
                    } else if (action == MotionEvent.ACTION_UP
                            || action == MotionEvent.ACTION_CANCEL) {
                        Toast.makeText(MainActivity.this, "Released", Toast.LENGTH_SHORT).show();
                        secondTime=System.currentTimeMillis();
                        if(secondTime-firstTime>=5000){
                            //do your actions here,prev,curr are fields in a class
                            ShowDialog();
                        }
                        else{
                            firstTime=0;
                            secondTime=0;
                        }
                    }
                    // TODO Auto-generated method stub
                    return false;
                }
            });

Solution

  • Change your OnTouchListener like this:

    hidenBtn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getActionMasked();
                if (action == MotionEvent.ACTION_DOWN) {
                    firstTime=System.currentTimeMillis();
                    Toast.makeText(MainActivity.this, "Pressed", Toast.LENGTH_SHORT).show();
                    return true;
                } else if (action == MotionEvent.ACTION_UP
                        || action == MotionEvent.ACTION_CANCEL) {
                    Toast.makeText(MainActivity.this, "Released", Toast.LENGTH_SHORT).show();
                    secondTime=System.currentTimeMillis();
                    if(secondTime-firstTime>=5000){
                        //do your actions here,prev,curr are fields in a class
                        ShowDialog();
                    }
                    else{
                        firstTime=0;
                        secondTime=0;
                    }
                }
                // TODO Auto-generated method stub
                return false;
            }
        });
    

    You are returning false at ACTION_DOWN which means you are not consuming your touch event, so no other steps of the same event are triggered. Therefore you need to return true in the ACTION_DOWN so you can intercept ACTION_UP.