我有一个密码对话框类,可以在想要删除或添加时询问密码。我想要的是可以一次又一次地重复使用这个对话框。
这是我的密码对话框类看起来像
public static class myPasswordDialog extends DialogFragment {
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.password_dialog, null))
.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
EditText passField = (EditText) ((AlertDialog) dialog).findViewById(R.id.password);
String password = passField.getText().toString();
if (password.matches(getString(R.string.pass_key))) {
//it should do something when it is correct
} else {
Toast.makeText(getActivity(), "Wrong Password", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
return builder.create();
}
}
这就是我调用密码类的方式
deletebtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myPasswordDialog mPasswordDialog = new myPasswordDialog();
mPasswordDialog.show(getFragmentManager(), "delete");
}
});
我的想法是,如果片段输入正确或错误的密码,它将返回一个布尔值。但我能以什么方式做到这一点?
答案 0 :(得分:2)
实施界面并设置回电
public static class MyPasswordDialog extends DialogFragment {
public interface MyCallBack {
public void onResult(boolean b);
}
public MyCallBack callBack;
public MyPasswordDialog(MyCallBack callBack) {
this.callBack = callBack;
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// your code
public void onClick(DialogInterface dialog, int id) {
EditText passField = (EditText) ((AlertDialog) dialog).findViewById(R.id.password);
String password = passField.getText().toString();
if (password.matches(getString(R.string.pass_key))) {
callBack.onResult(true); // pass false depends on condition
} else {
// code
}
}
}
}
如何致电
deletebtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
myPasswordDialog mPasswordDialog = new MyPasswordDialog(new MyPasswordDialog() {
@Override
public void onResult(boolean result) {
// result will be your ans
}
});
mPasswordDialog.show(getFragmentManager(), "delete");
}
});