OnLongClickListener to lock/unlock Toggle Button operation

▼魔方 西西 提交于 2019-12-12 03:32:18

问题


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


来源:https://stackoverflow.com/questions/35719954/onlongclicklistener-to-lock-unlock-toggle-button-operation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!