Search code examples
androidandroid-dialog

How to use Android's (non-modal) dialogs?


I'm a semi-newbie to Android and I'm not sure I see the "big picture" with regard to using Android's non-modal dialogs. I'm able to put up dialogs of many types but I don't know how to use the results after I click "Ok". It is clear that when a dialog is displayed, the calling UI task goes on it's merry way. Clearly, the purpose of any non-trivial dialog is to get some information from the user for further processing, but the main thread has already moved on. So how do I use the results of the dialog data to actually do something?

The only way I can see to do this is to put my results processing in the onclick handler of the "Ok" button, but that seems rather awkward and ungainly to my way of thinking. Nonetheless, is that the "usual and customary" way of processing dialog results? Is there a better way? Or am I massively missing something?

As a concrete example, say I want to display a list of files in a list view and select one to delete. Do I put the the delete-code in the onclick handler?


Solution

  • Yes, that's the "usual and customary" way of working with Android dialogs. You process the results in listeners, see the examples in dialogs guide or date picker dialog sample in the documentation.

    When you create the dialog with an activity (you have to set proper theme of the activity), you can do the processing in listeners in the dialog activity. Or you can return the values to the parent activity and process them in onActivityResult callback.

    The code you run in the listeners should be rather short and quick because it runs on the main thread. Never let the user wait! If the processing is time consuming do it in a the background.

    One note to modal vs. non-modal (modeless) dialogs in Android. By default all the dialogs (and the activities displayed as dialogs) are modal. You can create modeless dialogs (and activities displayed as dialogs) by setting proper window flags (for more details see this question and answer).