PX *_*per 6 android android-alertdialog android-dialogfragment
我有一个自定义布局的AlertDialog(只是一个EditText),我想在单击确定按钮时验证数据.如果验证失败,我不想关闭对话框.
我正在使用对话框的默认按钮(正面和负面).如果我使用"setPositiveButton("",new DialogInterface.OnClickListener()..."对话框总是关闭的.我看过几个帖子,他们说onClick Listener应该被覆盖,但我不能让它工作这是我发现的代码:
Button theButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
theButton.setOnClickListener(new CustomListener(dialog));
Run Code Online (Sandbox Code Playgroud)
因为它说它应该在显示对话框之后完成,所以我把这个代码放在我的活动中,而不是在我的DialogFragment中,但是如果我使用mDialogFragment.getDialog()它总是返回null.
这是我的Dialog片段的一部分:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.new);
LayoutInflater inflater = getActivity().getLayoutInflater();
dialogView = inflater.inflate(R.layout.edit_license, null);
builder.setView(dialogView)
// Add action buttons
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MyDialogFragment.this.getDialog().cancel();
}
});
return builder.create();
}
Run Code Online (Sandbox Code Playgroud)
在我的活动中,我执行以下操作:
DialogFragment dialog = new MyDialogFragment(true, null);
dialog.show(getSupportFragmentManager(), "EditLicenseDialogFragment");
AlertDialog alertDialog = (AlertDialog)dialog.getDialog();
alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
btnPositive.setOnClickListener(new CustomListener(alertDialog));
...
class CustomListener implements View.OnClickListener {
private final Dialog dialog;
public CustomListener(Dialog dialog) {
this.dialog = dialog;
}
@Override
public void onClick(View v) {
...
}
}
Run Code Online (Sandbox Code Playgroud)
就像我说的,(AlertDialog)dialog.getDialog(); 始终返回null.这是为什么?如果验证不正确,如何避免关闭对话框?
谢谢!
小智 5
这个解决方案对我有用。Dialog 已经在 onResume 中可见,因此这是访问按钮和替换侦听器的好地方。
public class XYZFragment extends DialogFragment {
...
@Override
public void onResume() {
super.onResume();
AlertDialog dialog = (AlertDialog)getDialog();
Button positiveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
positiveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View onClick) {
...
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
这是DialogFragment参考中的一些文本:
显示对话框窗口的片段,浮动在其活动窗口的顶部。该片段包含一个 Dialog 对象,它根据片段的状态适当显示该对象。对话框的控制(决定何时显示、隐藏、关闭它)应通过此处的 API 完成,而不是直接调用对话框。
而不是调用getDialog().dismiss()你应该做dismiss()
| 归档时间: |
|
| 查看次数: |
8420 次 |
| 最近记录: |