Android 如何在此AlertDialog中引入onBackButtonPressed方法?
我有一个alertDialog,但当我点击后退按钮时,什么都没有发生:Android 如何在此AlertDialog中引入onBackButtonPressed方法?,android,android-studio,Android,Android Studio,我有一个alertDialog,但当我点击后退按钮时,什么都没有发生: public class LocationQueries { Activity context; public LocationQueries(Activity context){ this.context = context; } protected void promptUserToActivateGps() { AlertDialog.Builder a
public class LocationQueries {
Activity context;
public LocationQueries(Activity context){
this.context = context;
}
protected void promptUserToActivateGps() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder
.setMessage(
"GPS is disabled in your device. Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Enable GPS",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
promptUserToActivateGps();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
如何引入onBackButtonPressed方法
更新:我更新了代码。当我在活动中使用它时,我会这样做:
private LocationQueries locationQueries = new LocationQueries(this);
locationQueries.promptUserToActivateGps();
更新:这是我能想到的一种实现您想要做的事情的方法。基本上,将
AlertDialog
返回到Activity
的onBackPressed
-方法中的Activity
,并执行与我之前的回答相同的操作。代码如下:
public class LocationQueries {
Activity context;
AlertDialog alert; // Declare the dialog
public LocationQueries(Activity context){
this.context = context;
}
protected void promptUserToActivateGps() {
/* Your method, except change this: */
alert = alertDialogBuilder.create();
alert.show();
}
// Add a getter for your dialog
public AlertDialog getAlertDialog() {
return alert;
}
}
public class YourActivity extends Activity {
/* Your other code */
private LocationQueries locationQueries = new LocationQueries(this);
@Override
public void onBackPressed() {
AlertDialog alert = locationQueries.getAlertDialog();
if(alert != null && alert.isShowing()) {
alert.getButton(DialogInterface.BUTTON_NEGATIVE).performClick();
}
}
}
最终编辑:正如
alexc
的回答中所述,通过使用AlertDialog
的setOnCancelListener
,在对话框打开时按下后退按钮,只要AlertDialog.Builder.setCancelable()
设置为true
我不想忽略它。我想做的和取消按钮一样。我应该在哪里添加它?通常在按下后退按钮时,或者在对话框可见时按下后退按钮时?仅当对话框可见时。在用户激活该位置之前,该对话框一直可见。@BogdanDaniel,请参阅我的更新答案。这就是你要找的吗?对不起,我不太了解你的结构,你能用所有相关的代码更新你的问题吗?