gpt4 book ai didi

android - 检查 DialogFragment 中的 EditText 值

转载 作者:行者123 更新时间:2023-12-05 00:07:04 26 4
gpt4 key购买 nike

我正在显示一个 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.");
}
}
}

最佳答案

尝试将文本更改监听器应用于您的 EditText 并在该监听器上使用 InputFilter。然后您可以在该过滤器中执行验证逻辑。

在您的情况下,您可能根本不需要该过滤器,您只需在监听器逻辑中进行检查即可。例如

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();
}

});

关于android - 检查 DialogFragment 中的 EditText 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28053623/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com