Skip to content

Instantly share code, notes, and snippets.

@dhawalhshah
Created November 10, 2011 17:45
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save dhawalhshah/1355547 to your computer and use it in GitHub Desktop.
Save dhawalhshah/1355547 to your computer and use it in GitHub Desktop.
Showing a Progress dialog using DialogFragment in Android
public class ProgressDialogFragment extends DialogFragment {
public static LoadingDialogFragment newInstance() {
ProgressDialogFragment frag = new ProgressDialogFragment ();
return frag;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final ProgressDialog dialog = new ProgressDialog(getActivity());
dialog.setMessage(getString(R.string.loading_text));
dialog.setIndeterminate(true);
dialog.setCancelable(false);
// Disable the back button
OnKeyListener keyListener = new OnKeyListener() {
@Override
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
if( keyCode == KeyEvent.KEYCODE_BACK){
return true;
}
return false;
}
};
dialog.setOnKeyListener(keyListener);
return dialog;
}
}
@AShuba
Copy link

AShuba commented Dec 16, 2012

"public static LoadingDialogFragment newInstance() {" must be changed to "ProgressDialogFragment"

@d-tarasov
Copy link

onKey method body could be simplified to return keyCode == KeyEvent.KEYCODE_BACK;

@Sash0k
Copy link

Sash0k commented Mar 21, 2014

to make it uncancellable you can use

this.setCancelable(false);

instead of

// Disable the back button
OnKeyListener keyListener = new OnKeyListener() { 
  @Override
  public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
   ...
  } 
};
dialog.setOnKeyListener(keyListener);

also dialog.setCancelable(false); is useless

@m3kwong
Copy link

m3kwong commented Jul 6, 2014

Agreed with Sash0k, shortens code just go setCancelable(false);

@perchrh
Copy link

perchrh commented Aug 18, 2014

Should also call dialog.setCanceledOnTouchOutside(false), otherwise user can dismiss it

@hegazy
Copy link

hegazy commented Feb 26, 2015

Added an updated gist with the fixes above.
1- "public static LoadingDialogFragment newInstance() {" must be changed to "ProgressDialogFragment".
2- We use this.setCancelable(false); to make it uncancellable rather than the OnKeyListener and add this as an option when creating a new instance.
3- An option to set a message when creating an instance.
...

https://gist.github.com/hegazy/796ba03d98b9ee68fab1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment