在實際開發中經常會用到showDialog(int id)的方法來展示一個對話框,但是會遇到一個Dialog展示之后下次再show的時候對話框的界面還是上次展示的那個,而不是我們想象的界面。很多時候我們打開一個對話框的時候里面的元素是根據需求變化的,這個時候就遇到刷新對話框的問題。這個時候就需要用到重寫onPrepareDialog方法了
現在有兩方面需求:
1、對話框的title或者message,這個時候在onPrepareDialog里面加上以下代碼就可以:
public void onPrepareDialog(int id, Dialog dialog) {
switch(id) {
case (TIME_DIALOG) :
String string = "";
AlertDialog timeDialog = (AlertDialog)dialog;
timeDialog.setMessage(string);
timeDialog.setTitle(string);
break;
}
}
但是有的時候我們要改變的不僅僅是title和massage,有可能對話框里面的布局是自定義的布局,我們要改變的是自定義布局里面的數據,這個時候我們期望的是每一次打開此對話框都可以重新加載一遍。代碼如下:
public void onPrepareDialog(int id, Dialog dialog) {
switch(id) {
case (TIME_DIALOG) :
removeDialog(id);
break;
}
}
這個時候可能會遇到在對話框中調用
removeDialog(ID)報錯的情況,解決辦法是
case ID: {
final String []citys = getServiceType();
Alert_Dialog dialog = new Alert_Dialog.Builder(NetDataPreferences.this).setTitle(R.string.netdata_adjust_order_service_type).setSingleChoiceItems(citys, getLocation(citys,0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
try {
dialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
}
}
}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
try {
dialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
}
}
}).create();
return dialog;
}
switch(id) {
case (TIME_DIALOG) :
String string = "";
AlertDialog timeDialog = (AlertDialog)dialog;
timeDialog.setMessage(string);
timeDialog.setTitle(string);
break;
}
}
但是有的時候我們要改變的不僅僅是title和massage,有可能對話框里面的布局是自定義的布局,我們要改變的是自定義布局里面的數據,這個時候我們期望的是每一次打開此對話框都可以重新加載一遍。代碼如下:
public void onPrepareDialog(int id, Dialog dialog) {
switch(id) {
case (TIME_DIALOG) :
removeDialog(id);
break;
}
}
這個時候可能會遇到在對話框中調用
removeDialog(ID)報錯的情況,解決辦法是
case ID: {
final String []citys = getServiceType();
Alert_Dialog dialog = new Alert_Dialog.Builder(NetDataPreferences.this).setTitle(R.string.netdata_adjust_order_service_type).setSingleChoiceItems(citys, getLocation(citys,0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
try {
dialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
}
}
}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
try {
dialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
}
}
}).create();
return dialog;
}