LJSilver
LJSilver

Reputation: 613

Is it correct to create a DialogFragment in an activity directly without using newInstance/setArguments?

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?

Upvotes: 1

Views: 87

Answers (3)

user3811368
user3811368

Reputation: 183

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.

Upvotes: 1

Egor
Egor

Reputation: 40218

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.

Upvotes: 0

CChi
CChi

Reputation: 3134

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

Upvotes: 0

Related Questions