У меня есть DialogPreference (точнее, EditTextPreference) и я хочу выполнить некоторые проверки значения, введенного пользователем. Эти проверки должны выполняться, когда пользователь нажимает «ОК», а не во время набора текста. Если все в порядке, диалоговое окно закроется. Если есть ошибка, появится AlertDialog с объяснением, что не так, и кнопкой ok. Этот AlertDialog должен отображаться «поверх» диалогового окна DialogPreference, и при нажатии кнопки «ОК» снова появляется первое диалоговое окно.
Я попытался расширить EditTextPreference и переопределить метод onClick (диалог DialogInterface, int which), чтобы сделать это:
@Override
public void onClick(DialogInterface dialog, int which) {
boolean invalidData = false;
// check input
if (true) {
invalidData = true;
}
if (which == DialogInterface.BUTTON_POSITIVE && invalidData) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage("Some message.")
.setCancelable(false)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).create().show();
//super.showDialog(new Bundle());
} else {
super.onClick(dialog, which);
}
}
Но это не имеет должного эффекта:
- В приведенном выше коде отображается AlertDialog, и значение не сохраняется при нажатии положительной кнопки EditTextPreference, но диалоговое окно EditTextPreference немедленно закрывается.
- Если super.showDialog (новый пакет ()); раскомментирован, отображается диалоговое окно AlertDialog
, а над ним сразу же снова появляется диалоговое окно EditTextPreference
.
Итак, как я могу достичь желаемого поведения?
EDIT: Поскольку, согласно hackbod, это невозможно, я буду использовать решение, которое подходит ближе. Это далеко не лучший пользовательский интерфейс, но поскольку мое приложение будет использоваться менее чем 100 людьми, и я разрабатываю его в свободное время, я не хочу прилагать к нему слишком много усилий, например, создавать свой собственный DialogPreference. Это то, что я использую сейчас:
public abstract class EditTextPreferenceWithCheck extends EditTextPreference {
private boolean mAlertDialogActive;
private String mCachedValue;
private String mMessage = "";
public EditTextPreferenceWithCheck(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public EditTextPreferenceWithCheck(Context context, AttributeSet attrs) {
super(context, attrs);
}
public EditTextPreferenceWithCheck(Context context) {
super(context);
}
/**
* Sets the message that will be shown if inputIsValid(String input) returns
* false.
*
* @param message The message to show
*/
protected void setMessage(String message) {
this.mMessage = message;
}
/**
* Checks if the user input is valid. If not, the message set with
* setMessage(String message) will be shown.
*
* @param input Current value in the text field
* @return true if the current value in the text field is valid, otherwise
* false
*/
protected abstract boolean inputIsValid(String input);
@Override
public void onClick(DialogInterface dialog, int which) {
if (mAlertDialogActive) {
mAlertDialogActive = false;
showDialog(new Bundle());
getEditText().setText(mCachedValue);
} else {
if (which == DialogInterface.BUTTON_POSITIVE
&& !inputIsValid(getEditText().getText().toString())) {
mAlertDialogActive = true;
mCachedValue = getEditText().getText().toString();
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setMessage(mMessage)
.setCancelable(false)
.setPositiveButton(android.R.string.ok, this).show();
} else {
super.onClick(dialog, which);
}
}
}
}