Android:为什么这个对话框会弹出两次?
我有一个对话框可以检查互联网是否已打开。如果它没有打开,我会显示一个弹出窗口,让您可以选择打开数据或退出应用程序。如果您选择打开数据,它将带您进入设置页面以打开数据。问题是:当您从设置页面按返回时,对话框仍然存在,但不会被关闭。这是代码:
public void calldialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"You need to enable an internet connection in order to use this Chirps:")
.setCancelable(true)
.setPositiveButton("Turn on Data",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent newintent = new Intent(
android.provider.Settings.ACTION_WIRELESS_SETTINGS);
newintent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(newintent);
dialog.dismiss();
}
})
.setNegativeButton("Exit",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Main.this.finish();
}
});
builder.show();
}
当我只有一个选项时,对话框可以正常运行。但是,一旦我添加第二个选项,它就会导致按钮显示两次。包含 calldialog() 的互联网检查函数在 oncreate 和 onresume 中都被调用,这可能是问题的一部分。
I have a dialog that checks to see if the internet is on. If it isn't on, I display a pop-up giving you the option to turn data on or exit the app. If you choose to turn data on it will take you to the settings page to turn data on. Here is the problem: When you press back from the settings page the dialog is still present, it doesn't get dismissed. Here is the code:
public void calldialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"You need to enable an internet connection in order to use this Chirps:")
.setCancelable(true)
.setPositiveButton("Turn on Data",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent newintent = new Intent(
android.provider.Settings.ACTION_WIRELESS_SETTINGS);
newintent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(newintent);
dialog.dismiss();
}
})
.setNegativeButton("Exit",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Main.this.finish();
}
});
builder.show();
}
When I only had one option the dialog functioned properly. But as soon as I add the second option it causes the button to show twice. The internet check function in which the the calldialog() is contained is called in both the oncreate and onresume which may be part of the problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在dialog.dismiss()之前调用startActivity()。这可以控制新的活动。
You call startActivity() before dialog.dismiss(). This gives control to the new activity.
首先,当您在 Android 中启动应用程序时,活动顺序如下:
活动启动 -->
onCreate()
被调用 -->onResume()
被调用 -->活动正在运行。当您从设置返回应用程序时,
onResume()
会被调用,因此您只需在onResume()
中进行检查。First of all, when you start your app in android the activitysequens are as follows:
activity starts -->
onCreate()
is called -->onResume()
is called --> activity is running.When you go from setting and back to your app
onResume()
is called, so you only need to make the check inonResume()
.