我的活动中有一个切换按钮。当开关为 On 时,显示启用对话框,开关为 Off 时,显示禁用对话框。
((SwitchCompat) findViewById(R.id.toggleButton)).setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
((StyleableTextView) findViewById(R.id.lbl_toggle_status)).setText("on");
showEnableSharingDialog();
} else {
((StyleableTextView) findViewById(R.id.lbl_toggle_status)).setText("off");
showDiasableShareingDialog();
}
}
});
这是启用对话框:
private void showEnableShareingDialog() {
final CharSequence options[]= getResources().getStringArray(R.array.sharing_options);
AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this);
builder.setTitle(getString(R.string.you_want_to_enable_prev_sigtings));
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(which==0){
mShareSigtings=true;
mEnableShareing=true;
updateSettings();
} else if(which==1){
mShareSigtings=true;
mEnableShareing=false;
updateSettings();
} else {
/*---todo---*/
dialog.cancel();
}
}
});
builder.show();
}
这是禁用对话框:
private void showDiasableShareingDialog() {
final CharSequence options[]= getResources().getStringArray(R.array.remove_sharing_options);
AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this);
builder.setTitle(getString(R.string.you_want_to_remove_prev_sigtings));
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
mShareSigtings = false;
mRemovePrevSigtings = true;
updateSettings();
} else if (which == 1) {
mShareSigtings = false;
mRemovePrevSigtings = false;
updateSettings();
} else {
/*---todo---*/
dialog.cancel();
}
}
});
builder.show();
}
在这两个对话框中,切换按钮切换它的状态,即说切换处于 ON 状态,然后我按下按钮,对话框弹出,当我按下 CANCEL 时,它从 ON 状态变为 OFF 状态。预期结果是当按下 CANCEL 时,切换按钮应保持在其原始位置,即,如果切换为 ON,则在按下 CANCEL 时应保持 ON。我将如何实现这种操作?
此外,如果我执行以下操作,则两个对话框都会在按下 CANCEL 时不断弹出。
if(((SwitchCompat)findViewById(R.id.toggle3)).isChecked()){
((SwitchCompat)findViewById(R.id.toggle3)).setChecked(false);
}else {
((SwitchCompat)findViewById(R.id.toggle3)).setChecked(true);
}