我有一個DialogPreference(更確切地說是一個EditTextPreference),並且希望對用戶輸入的值執行一些檢查。這些檢查應在用戶點擊確定時進行,而不是在他正在鍵入時進行。如果一切正常,對話框應關閉。如果出現錯誤,AlertDialog將出現,並解釋什麼是錯誤的,以及確定按鈕。這個AlertDialog應該在DialogPreference對話框的「頂部」顯示出來,當點擊OK按鈕時,第一個對話框將再次出現。當點擊OK時顯示AlertDialog「DialogPreference頂部」
我試圖擴大EditTextPreference並重寫的onClick(DialogInterface對話框,INT其中)方法來做到這一點:
@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(new Bundle());沒有註釋,則顯示AlertDialog
,並在其上方立即再次彈出EditTextPreference的
對話框。
那麼我該如何達到理想的行爲呢?
編輯:由於根據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);
}
}
}
}
很遺憾。我現在使用某種解決方法,我編輯了我原來的帖子。它看起來不太好,但它適合我的需求。感謝你的回答! –