Seb*_*ian 5 java android android-alertdialog
我已经尝试学习和使用 Android Studio 大约 3 周了。我刚刚遇到了一种情况,即 AlertDialogue 在点击肯定按钮时不会关闭。
private void showGPSDisabledAlertToUser() {
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(this);
}
builder.setTitle("Turn On Location / GPS");
builder.setCancelable(false);
builder.setMessage("Application Needs To Determine Device's Physical Location.");
builder.setPositiveButton("YES, TURN ON", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss(); // This ain't working
goToInternetSettings();
}
});
builder.setNegativeButton("NO, CANCEL", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
closeApplication();
}
});
builder.create().show();
}
private void goToInternetSettings() {
Intent gpsSetting = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsSetting);
}
private void closeApplication() {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
Run Code Online (Sandbox Code Playgroud)
看起来我只能在必须双击肯定时才能关闭对话。
另一方面,使用否定按钮则没有这样的麻烦。我想,因为否定按钮会关闭整个应用程序,因此正在解决这个问题,否则它会是一样的。
您不需要在dialog.dismiss()内部调用,setPositiveButton() OnClickListener因为它是隐式调用的。
showGPSDisabledAlertToUser()检查 GPS 可用性时,您可能会多次拨打电话。您可以尝试创建一次对话框,然后使用以下内容重新显示:
AlertDialog mAlertDialog;
private void showGPSDisabledAlertToUser() {
// build the alert dialog once.
if (mAlertDialog == null) {
AlertDialog.Builder builder;
...
// Do your dialog initialization here.
...
mAlertDialog = builder.create();
}
mAlertDialog.show();
}
Run Code Online (Sandbox Code Playgroud)
您不需要通过调用对话框界面按钮的方法dialog.dismiss();来显式关闭警报对话框。onClick
单击任何这些按钮后,该对话框将自动关闭。
如果您告诉单击该按钮后该对话框并未消失,则您可能创建了多个对话框,因此即使一个对话框被关闭,另一个对话框仍然存在。
| 归档时间: |
|
| 查看次数: |
2380 次 |
| 最近记录: |