1

The "accademic" way to pass arguments to a DialogFragment is the newInstance method with setArguments(.). But to make things easy one can simply:

class D extends DialogFragment{
    public Context ctx;
    public D newInstance(Context c){
        D d = new D();
        d.ctx = c;
        //...
        return d;
    }
}

Or this is possible also in the activity code

D d = new D();
d.some_data = other_data;
d.show(...);

Thus why to use the newInstance-setArgument scheme that is much more unconfortable?

4

3 回答 3

1

Using the arguments method is preferred because arguments survive orientation changes and fragment destroy / resume cycle. This means that if for some reason the dialog is destroyed and later resumed, the state is preserved. If you directly manipulate the fields, the fragment can’t save it’s state.

Not using the arguments pattern is a common reason for random application crashes when resuming to the app. You can test this by going to device developer options and checking the “Don’t keep activities” option.

于 2014-09-04T20:32:59.950 回答
0

You should be using the setArgument pattern if you would like preserve those variable's value after an orientation change.

于 2014-09-04T20:30:48.117 回答
0

When the Fragment is re-created, e.g. on device rotation, the arguments stored in Bundle will be preserved, so you'll be able to retrieve them again in onCreate(). Fields that you initialize directly will be nullified.

于 2014-09-04T20:31:09.867 回答