OnLongClickListener用于锁定/解锁切换按钮操作

时间:2016-03-01 10:06:35

标签: java android togglebutton onlongclicklistener

我正在尝试在Toggle Button上使用长按一下监听器来锁定/解锁按钮的正常点击操作(以避免意外点击)。以下代码似乎没有任何效果。我没有运气就尝试了.isActivated.isCickable.isEnabled属性......这可能吗?

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

2 个答案:

答案 0 :(得分:0)

您需要将代码段更改为

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

答案 1 :(得分:0)

也许使用布尔值?

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

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