Reject non-cancellable dialog on backPress snippet - Android

I have navigation box activity and lots of fragments that I get through the navigation box.

In some of these snippets, I show a dialog that says "Loading .." when background tasks are performed.

Now I have made my dialogs not canceled on dialog.setCancelable(false) so that the user does not accidentally reject it by clicking anywhere on the screen. This makes it impossible to cancel even when the back button is pressed.

This is the code for my dialogue -

 Dialog dialog = new Dialog(context); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.custom_progress_dialog); ((TextView)dialog.findViewById(R.id.custom_dialog_message)).setText("Loading ..."); dialog.setCancelable(false); dialog.show(); 

I need to write code to close the download dialog and go to the previous fragment when the "Back back" button on any fragment is clicked.

Can someone help me? Basically I need to implement fragment specific backPress. Thanks!

+5
source share
3 answers

you can use getFragmentManager().popBackStackImmediate();

 dialog.setOnKeyListener(new Dialog.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { // TODO Auto-generated method stub if (keyCode == KeyEvent.KEYCODE_BACK) { dialog.dismiss(); getFragmentManager().popBackStackImmediate(); } return true; } }); 
+6
source

It's just like that.

 dialog.setOnKeyListener(new Dialog.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { // TODO Auto-generated method stub if (keyCode == KeyEvent.KEYCODE_BACK) { dialog.dismiss(); } return true; } }); 
+6
source

Delete the line of code:

 dialog.setCancelable(false); 

and put it and try

 dialog.setCanceledOnTouchOutside(false); 

However, your dialogue will not be canceled if the user accidentally touches the screen, but if the user clicks the button, he will cancel

+5
source

Source: https://habr.com/ru/post/1232612/


All Articles