Android “Best Practice” returning values from a dialog

后端 未结 6 1654
闹比i
闹比i 2020-12-07 18:27

What is the \"correct\" way to return the values to the calling activity from a complex custom dialog - say, text fields, date or time picker, a bunch of radio buttons, etc,

6条回答
  •  猫巷女王i
    2020-12-07 19:20

    I've pondered over this myself for a while and eventually the most convenient way I found of doing this is breaking up my activity into various methods that represent each unit of control flow. For example, if the activities within my activity are say : load variables from intent, check for some data, process and proceed if available, if not make a background call, wait for user interaction, start another activity.

    I generally pickup the parts that are common, the first two and the last in this case. I'll wrap the first ones in onCreate() and make a separate one for the last... say startAnotherActivity(Data). You can arrange the middle parts so they'll consist of a checkData(Data) (possibly merged into the onCreate()) which calls either processAvailableData(Data) or performBackgroundTask(Data). The background task will perform an operation in the background and return control to onBackgroundTaskCompleted(OtherData).

    Now both processAvailableData(Data) and onBackgroundTaskCompleted(OtherData) call the getUserResponse() method which in turn may either call startAnotherActivity(Data) or merge its functions with itself.

    I feel this approach gives a number of benefits.

    1. It helps with the data return issue your question points to by "moving forwards" instead of returning data.
    2. It allows easier addition of new functionality. For instance, if we wanted to give the user more options, we could just call the appropriate method from getUserResponse() which could effect the data that is eventually passed to the next activity.
    3. It helps avoid needless flow problems (check out the questions relating to finish() and return on SO) when our intuitive assumption is a certain flow and it turns out to be another.
    4. Helps manage variables better so you don't end up having a lot of class level fields to avoid the variable access problems in anonymous inner classes (onClick(), doInBackground(), etc.).

    I'm pretty sure having more methods adds some overhead but its probably offset by the flow, reuse and simplicity advantages you get (would love to hear a compilation expert's views on this).

提交回复
热议问题