Search code examples
javaandroidtogglebuttononlongclicklistener

OnLongClickListener to lock/unlock Toggle Button operation


I am trying to use a Long-Click listener on a Toggle Button to lock/unlock the normal click action of the button (to avoid accidental clicking). The below code seems to have no effect. I have tried .isActivated, .isCickable and .isEnabled properties without luck... Is it possible?

final ToggleButton btnStartStop = (ToggleButton) findViewById(R.id.toggleAction);
    btnStartStop.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            // TODO Auto-generated method stub
            if (btnStartStop.isActivated()) {
                btnStartStop.setActivated(false);
            } else {
                btnStartStop.setActivated(true);
            }
            return true;
        }
    });

Solution

  • Maybe use a boolean?

    Boolean longPress = false;
    
    final ToggleButton btnStartStop = (ToggleButton) findViewById(R.id.toggleAction);
    btnStartStop.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            // TODO Auto-generated method stub
            if (longPress) {
                longPress = false;
            } else {
                longPress = true;
            }
            return true;
        }
    });
    

    and onClick():

    btnStartStop.setOnClickListener(new View.OnClickListener() {
    
        @Override
        public void onClick(View v) {
    
        if(!longPress){
            //Do stuff
        }
        else{
            Toast.makeText(getApplicationContext(), "Button is locked!\nLong press button to unlock it",Toast.LENGTH_SHORT).show();
        }
    });