我试图弄清楚如何在我的自定义DialogPreference中,点击positive_button,我可以执行检查,如果它无效,则打开对话框。如果它有效,我想关闭自定义DialogPreference
以下是我目前所拥有的,但无论是否有效,都会关闭对话框
public class PasswordDialogPreference extends DialogPreference {
TextView tvOldPassword;
TextView tvNewPassword;
TextView tvConfirmPassword;
EditText etOldPassword;
EditText etNewPassword;
EditText etConfirmPassword;
SharedPreferences sharedPrefs;
SharedPreferences.Editor editor;
public PasswordDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setDialogLayoutResource(R.layout.password_dialog_preference);
setPositiveButtonText(android.R.string.ok);
setNegativeButtonText(android.R.string.cancel);
setDialogIcon(null);
setPersistent(false);
}
@Override
public void onBindDialogView(View view) {
tvOldPassword = (TextView) view.findViewById(R.id.tvOldPassword);
tvNewPassword = (TextView) view.findViewById(R.id.tvNewPassword);
tvConfirmPassword = (TextView) view.findViewById(R.id.tvConfirmPassword);
etOldPassword = (EditText) view.findViewById(R.id.etOldPassword);
etNewPassword = (EditText) view.findViewById(R.id.etNewPassword);
etConfirmPassword = (EditText) view.findViewById(R.id.etConfirmPassword);
sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(getContext());
if (sharedPrefs.getString("prefPasscode", "").length() < 4) {
tvOldPassword.setVisibility(View.GONE);
etOldPassword.setVisibility(View.GONE);
}
super.onBindDialogView(view);
}
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
persistBoolean(positiveResult);
}
@Override
protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
super.onPrepareDialogBuilder(builder);
//builder.setNegativeButton(null, null);
builder.setPositiveButton(AlertDialog.BUTTON_POSITIVE, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(getContext());
if (etNewPassword.getText().toString().equals(etConfirmPassword.getText().toString())) {
editor.putString("prefPasscode", etConfirmPassword.getText().toString());
editor.commit();
Toast.makeText(getContext(), "Pin saved.",
Toast.LENGTH_SHORT
).show();
} else if (etNewPassword.getText().toString().length() != 4) {
Toast.makeText(getContext(), "Pin must be 4 digits.",
Toast.LENGTH_SHORT
).show();
} else if (!etNewPassword.getText().toString().equals(etConfirmPassword.getText().toString())) {
Toast.makeText(getContext(), "Pin does not match.",
Toast.LENGTH_SHORT
).show();
}
}
});
}
}
答案 0 :(得分:1)
尝试覆盖showDialog(Bundle)
方法以获取实际的AlertDialog
实例,并重置onClickListener
以获得肯定按钮:
@Override
protected void showDialog(Bundle state) {
super.showDialog(state);
final AlertDialog dlg = (AlertDialog) getDialog();
dlg.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (needToClose) {
dlg.dismiss();
}
}
});
}