问题
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