[英]Dismiss a custom dialog in the onClick handler of the dialog's Button and read dialog element's value
這非常重復此處的一個舊問題: 關閉自定義對話框?
雖然我了解可接受的解決方案,但讓類成員持有對對話框實例的引用並稍后使用parent.this.dialog.dismiss()將其關閉似乎並不正確。
另外,我不理解第二種解決方案,即使用:dismissDialog(DIALOG_ID);
我已經一遍又一遍地閱讀了文檔的那一部分,但是我不太理解為什么當我能夠在父級活動中使用該功能(除消除)時,需要在父級活動中實現OnCreateDialog等。活動的OnCreate:
ImageButton btnAdd = (ImageButton)findViewById(R.id.button_shoppinglists_add);
btnAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Dialog dialog = new Dialog(ShoppingListActivity.this,
R.style.Theme_AppCustomDialog);
dialog.setContentView(R.layout.dialog_addshoppinglist);
dialog.setCancelable(true);
// Set the on OK listener
Button okButton = (Button) dialog.findViewById(R.id.dialog_button_OK);
if (okButton != null) {
okButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.e("ShoppingListActivity:AddList", "OK");
// How to dismiss the dialog here?????
// doing the following does not feel right:
// parentActivity.this.mCustomDialog.dissmiss()
// where mCustomDialog holds a reference to the
// dialog just created
}
});
}
編輯1:我還想到,我不知道如何讀取對話框中可能存在的EditText字段的值,因為我在按鈕的onClick處理程序中沒有對該對話框的引用。
編輯2:進行了大量挖掘,似乎無法像我想要的那樣使用AlertDialog。 如建議的那樣,我將實現更改為改為使用AlertDialog:
ImageButton btnAdd = (ImageButton) findViewById(R.id.button_shoppinglists_add);
btnAdd.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// inflate the view from resource layout
LayoutInflater inflater = (LayoutInflater)
shoppingListActivity.this.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
final View dialogView = inflater.inflate(
R.layout.dialog_addshoppinglist, (ViewGroup)
findViewById(R.id.dialog_addshoppinglist_root));
AlertDialog dialog = new AlertDialog.Builder(ShoppingListActivity.this)
.setView(dialogView)
.setTitle(getResources().getString(R.string.shoppinglist_add_title))
.create();
dialog.setButton(DialogInterface.BUTTON1, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
EditText editListName = (EditText) dialogView.findViewById(
R.id.dialog_addshoppinglist_editTextName);
String listName = editListName.getText().toString();
dialog.dismiss();
}
});
}
}
事實證明,該技巧是在視圖對象上使用final關鍵字,如下所示:
final View dialogView = inflater.inflate(
R.layout.dialog_addshoppinglist, (ViewGroup)
findViewById(R.id.dialog_addshoppinglist_root));
現在,dialogView對象在DialogInterface.onClickListener中可用。 您可能已經猜到了,我是JAVA的新手:)
此處記錄的詳細信息
謝謝M @ nish
除了使用View.OnClickListener之外,還可以使用DialogInterface.OnClickListener並在onClick()方法的新實現內部調用dialog.dismiss(),因為您已經將對話框作為onClick方法的參數。
如果您還有其他疑問,請告訴我。
謝謝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.