Created
November 10, 2011 17:45
-
-
Save dhawalhshah/1355547 to your computer and use it in GitHub Desktop.
Showing a Progress dialog using DialogFragment in Android
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
onKey
method body could be simplified to return keyCode == KeyEvent.KEYCODE_BACK;
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
Agreed with Sash0k, shortens code just go setCancelable(false);
Should also call dialog.setCanceledOnTouchOutside(false), otherwise user can dismiss it
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.
...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
"public static LoadingDialogFragment newInstance() {" must be changed to "ProgressDialogFragment"