我的GPSTracker中有这个方法:
public void showSettingsAlert() {
final AlertDialog.Builder alertDialog = new AlertDialog.Builder(myContext);
// Setting Dialog Title
alertDialog.setTitle("GPS Settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// Setting Icon to Dialog
// alertDialog.setIcon(R.drawable.delete);
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
myContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
当我运行它的时候,我会一次得到10个对话框,所以基本上我可以按10次取消或类似的键,我该如何修复它?我读过
final AlertDialog alert = alertDialog.create();
if(alert.isShowing()) {
alert.dismiss();
}
else {
alert.show();
}
但这对我来说不起作用,我仍然有多个对话框。。。有人能帮我吗?基本上我调用if(gps.isEnabled())gps.showSettingsAlert();在我的活动中。
if (itemsArrayList.get(position).getCoordinates() == null || !gps.canGetLocation()) {
holder.distance.setText("Distance not available");
gps.showSettingsAlert();
}
我认为Phan Văn Linh提供的解决方案是关键,只需要一些小的修改。
-
首先,将alertDialog作为活动或应用程序(取决于您)的全局变量,并将其初始化为null。
private AlertDialog.Builder _AlertDialog=null;
null初始化将帮助您检查alertDialog的实例是否已创建。
-
然后将showSettingDial设置为这样:
公共void showSettingsAlert(){if(_alertDialog!=null){//在这里我们检查是否显示了实例回来}
_alertDialog=新建alertDialog.Builder(myContext);//设置对话框标题。。。_alertDialog.show();}
-
最后,当对话框被取消时,使实例再次为null。
_alertDialog=null;
将alertDialog
作为Activity类的全局变量
然后在showSettingsAlert()
中,您可以检查警报是否显示。
private AlertDialog alertDialog;
...
public void showSettingsAlert() {
if( alertDialog != null && alertDialog.isShowing() ){
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// Setting Dialog
//builder.setTitle(...)
//builder.setMessage...
//builder.setPositiveButton...
//builder.setNegativeButton...
...
alertDialog= builder.create();
alertDialog.show();
}
希望这能帮助