OnLongClickListener to lock/unlock Toggle Button o

2019-09-01 09:32发布

问题:

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;
        }
    });

回答1:

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();
    }
});


回答2:

You need to change your snippet as

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 (togglePref.isChecked()==(true)) 
             {

             // button is checked

             }

            else
              {

               // button is unchecked 

               }

          return true; 
        } 
    });