[英]Show AlertDialog “on top of” DialogPreference when ok is clicked
我有一個DialogPreference(更確切地說是EditTextPreference),並希望對用戶輸入的值進行一些檢查。 這些檢查應在用戶單擊確定時進行,而不是在鍵入時進行。 如果一切正常,對話框將關閉。 如果有錯誤,將顯示一個AlertDialog並說明問題所在和確定按鈕。 該AlertDialog將在DialogPreference對話框的頂部“視圖”中顯示,並且當單擊“確定”按鈕時,第一個對話框將再次出現。
我試圖擴展EditTextPreference並重寫onClick(DialogInterface dialog,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);
}
}
但這並沒有達到預期的效果:
那么我怎樣才能達到期望的行為呢?
編輯:由於根據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);
}
}
}
}
抱歉,您不能執行此操作,在交付結果時,EditTextPreference會自動關閉其對話框,並且您不能阻止它執行此操作。
我建議您創建自己的DialogPreference,以便在點擊時顯示自己的自定義對話框。 您可以在該對話框中驗證文本,因為它是您自己的對話框。 這也將為您帶來更好的用戶體驗。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.