我需要 PreferenceActivity 中的 AutoCompliteTextView,所以我扩展了 DialogPreference。我的自动完成期望(帮助)用户输入国家名称。如果用户按取消或不输入任何值,我很好,但是我想确保在关闭对话框之前输入正确的名称。我试图将 onClick 重写为
@Override
public void onClick(DialogInterface dialog, int which) {
if (!validator.isValid(textView.toString())) {
onDialogClosed(false);
} else {
//do something here
super.onClick(dialog, which);
}
}
还有 onDialogClosed
@Override
protected void onDialogClosed(boolean positiveResult) {
if (validator.isValid(textView.toString())) {
//do something here
super.onDialogClosed(positiveResult);
}
}
最佳答案
我还遇到了一个问题,即 Android 不提供在首选项对话框关闭之前检查新输入的首选项值的内置方法。对话框关闭后进行检查(boolean onPreferenceChange
完成的),只能发现值不正确,应用程序应该阻止它被保存,但这似乎很不方便。试想一下,用户输入错误,新值没有保存,但对话框关闭,用户被告知他/她必须从头开始重复这个过程。它肯定应该被修复。
编程中遇到问题,最好能提供代码解决。这就是为什么我将答案与准备好复制和粘贴的解决方案一起发布的原因。它遵循上述答案之一的明显想法,但它并不像其他提供的代码 fragment 所暗示的那样处理反射。
public class CustomEditTextPreference extends EditTextPreference
{
// if true, this preference requires new values to be checked for conformance to e-mail syntax
private boolean isEmail = false;
public CustomEditTextPreference(Context context, AttributeSet attrs)
{
super(context, attrs);
// set isEmail either from custom XML-attributes (look up through attrs)
// or just by key
// if(getKey().equals(KNOWN_EMAIL_PREF))
// isEmail = true;
}
/**
* Checks if newValue conforms to a specific rule/syntax.
* Returns error code equal to resource ID of corresponding error message if the value is incorrect,
* or 0 if the validation was successful
*
* @param newValue a string with new preference value that needs a check-up
* @return integer error code equal to error message resource id
*/
private int isValid(String newValue)
{
int result = 0; // no error
if(isEmail)
{
if(!android.util.Patterns.EMAIL_ADDRESS.matcher(newValue).matches())
{
result = R.string.invalid_email;
}
}
// ...
// other check-ups if necessary
return result;
}
@Override
protected void showDialog(Bundle state)
{
super.showDialog(state);
final AlertDialog d = (AlertDialog)getDialog();
final EditText edit = getEditText();
d.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
int errorCode = isValid(edit.getText().toString());
Boolean canCloseDialog = (errorCode == 0);
if(canCloseDialog)
{
d.dismiss();
onDialogClosed(true);
}
else
{
String errorMessage = getContext().getString(errorCode);
Toast t = Toast.makeText(getContext(), errorMessage, Toast.LENGTH_LONG);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
}
}
});
}
}
我认为代码几乎是不言自明的。如果用户在字段中填写了错误的电子邮件,并按下了 OK 按钮,则对话框保持打开状态并通过 toast 显示一条错误消息。
关于android - 如果条件不满足,不要关闭 DialogPreference onClick,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9966931/