我正在显示DialogFragment
提示用户提供输入。我想验证此输入(不应为空)并在验证失败时显示Toast
,而不关闭对话框。
目前,我在验证失败时显示Toast,但对话框被取消。我该如何防止这种情况?
DialogFragment类:
public class DialogFragmentAddNewFolder extends DialogFragment implements DialogInterface.OnClickListener {
private EditText etName;
private DialogFragmentAddNewFolderListener mListener;
public interface DialogFragmentAddNewFolderListener {
public void onAddNewFolderPositiveClick(Folder folder);
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View ourView = inflater.inflate(
R.layout.dialogfragment_add_note, null);
builder.setView(ourView);
etName = (EditText) ourView.findViewById(R.id.etAddFolder);
builder.setTitle(R.string.dialogfragment_add_folder_title);
builder.setPositiveButton(
R.string.dialogfragment_add_folder_pos_btn, this);
builder.setNegativeButton(
R.string.dialogframent_add_folder_neg_btn, this);
return builder.create();
}
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case DialogInterface.BUTTON_POSITIVE:
String name = etName.getText().toString();
if (name.equals("")) {
Toast.makeText(getActivity(), "Provide a name", Toast.LENGTH_SHORT).show();
} else {
Folder folder = new Folder();
folder.setName(name);
mListener.onAddNewFolderPositiveClick(folder);
}
break;
case DialogInterface.BUTTON_NEGATIVE:
dialog.dismiss();
break;
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (DialogFragmentAddNewFolderListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ "Must implement DialogFragmentAddNewFolderListener.");
}
}
}
答案 0 :(得分:0)
尝试将文本更改侦听器应用于EditText
并在该侦听器上使用InputFilter
。然后,您可以在该过滤器中执行验证逻辑。
在您的情况下,您可能根本不需要该过滤器,您只需在侦听器逻辑中进行检查即可。 e.g。
yourEditText.addTextChangedListener(new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
doYourChecking();
}
});