Android:如何防止后退button取消FragmentDialog
我有一个可以创build和popup一个DialogFragment的片段,但是当我点击后退button时,即使我明确地调用setCancelable(false),它也会closures对话框。 有没有办法让我的DialogFragment对后退button不敏感?
public class LoadingDialogFragment extends DialogFragment { String title; String msg; public LoadingDialogFragment() { this.title = "Loading..."; this.msg = "Please wait..."; } public LoadingDialogFragment(String title, String msg) { this.title = title; this.msg = msg; } @Override public Dialog onCreateDialog(final Bundle savedInstanceState) { final ProgressDialog dialog = new ProgressDialog(getActivity()); dialog.setTitle(title); dialog.setMessage(msg); dialog.setIndeterminate(true); dialog.setCanceledOnTouchOutside(false); dialog.setCancelable(false); return dialog; } }
我从asynctask创buildFragmentDialog:
private class GpsTask extends AsyncTask<String, Integer, Integer> { //ProgressDialog dialog; @Override protected void onPreExecute() { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); DialogFragment newFragment = new LoadingDialogFragment("Gathering Location", "Acquiring GPS lock..."); ft.addToBackStack(null); newFragment.show(ft, "dialog"); } @Override protected Integer doInBackground(String... params) { //acquire a GPS lock and grab a few position updates } @Override protected void onProgressUpdate(Integer... input) { } @Override protected void onPostExecute(Integer result) { getSupportFragmentManager().popBackStackImmediate(); } }
如何使用setCancelable
? 你试过了吗?
从文档 –
控制显示的对话框是否可取消。 使用它而不是直接调用Dialog.setCancelable(boolean),因为DialogFragment需要根据这个来改变它的行为
我一点也不确定这是否会与FragmentDialogs一起工作,但是如果setCancelable不适合你,那么看看这篇文章可能是值得的: Android:当按下Backbutton时提示用户保存更改
它解释了如何检测正在按下的后退button。 所以也许你可以压制button,它会停止对话框closures?
它可以帮助你。
newFragment.setCancelable(false);
在创buildDialogFragment对象时或在Custom DialogFragment的构造函数中进行如上所示的更改,如下面的示例中所示。
public static CustomClearHourDialog newInstance(Bundle args, IDialogListener listener) { CustomClearHourDialog clearHourDialog = new CustomClearHourDialog(); CustomClearHourDialog.listener = listener; clearHourDialog.setCancelable(false); return clearHourDialog; }