@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder
(getApplicationContext(), android.R.style.Theme_DeviceDefault);
builder.setTitle("Exit").setMessage("Do you really want to Exit ? ")
.setPositiveButton(" Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
System.exit(1);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
当我按下后退按钮时,此应用程序崩溃。
答案 0 :(得分:2)
您正在使用应用程序的上下文显示Dialog
。 Android中不允许这样做,因为Dialog
需要Activity
将自身附加到
更改此行
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext(), android.R.style.Theme_DeviceDefault);
进入这个
AlertDialog.Builder builder = new AlertDialog.Builder(this, android.R.style.Theme_DeviceDefault);
当您使用Activity
时(根据代码的外观),this
(第一个参数)会引用您当前的活动,因此这应该可以解决您的问题
答案 1 :(得分:1)
AlertDialog.Builder builder = new AlertDialog.Builder (this, android.R.style.Theme_DeviceDefault);
传递活动参考
答案 2 :(得分:0)
AlertDialog.Builder builder = new AlertDialog.Builder
(this, R.style.AppTheme);
builder.setTitle("Exit").setMessage("Do you really want to Exit ? ").setPositiveButton(" Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
System.exit(1);
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
答案 3 :(得分:0)
首先要做的事情。您无法显示带有应用程序上下文的对话框。 Dialog需要附加到某些活动,因此需要Activity上下文而不是Application Context。
您需要覆盖Activity's
onBackPressed()
方法来处理设备的后退键事件。
您可以这样写:
@Override
public void onBackPressed() {
confirmBeforeExit();
}
private void confirmBeforeExit() {
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setTitle("Exit")
.setMessage("Do you really want to Exit ? ")
.setPositiveButton(" Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).create();
alertDialog.show();
}