David Ibrahim
David Ibrahim

Reputation: 3227

How to make sure that fragment is created in the activity from static method new Instance

I am designing a fragment to be used by other developers. Fragments must have a public constructor that the android SDK use in creating fragments, but to pass data from the activity to fragment it's preferable to create a static method that creates the fragment in the Fragment class like this

  public static FaceMatchingResultFragment newInstance(boolean matched, String param2) {
        FaceMatchingResultFragment fragment = new FaceMatchingResultFragment();
        Bundle args = new Bundle();
        args.putBoolean(ARG_PARAM1, matched);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

My question is there a way to make sure that the developer have to use this method and not the public constructor ?

Upvotes: 2

Views: 238

Answers (1)

Pawel
Pawel

Reputation: 17268

Checking if argument bundle is included during onCreate is the cleanest way to do it without messing around with reflection. If you want to show inline error when accessing no-arg constructor you can use RestrictTo annotation:

public class SimpleArgFragment extends Fragment {
    public static SimpleArgFragment newInstance(boolean val) {
        Bundle args = new Bundle();
        args.putBoolean("param", val);
        SimpleArgFragment f = new SimpleArgFragment();
        f.setArguments(args);
        return f;
    }

    @androidx.annotation.RestrictTo({RestrictTo.Scope.SUBCLASSES})
    public SimpleArgFragment() {
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() == null)
            throw new IllegalArgumentException("Missing arguments - use newInstance() to create.");
    }
}

Upvotes: 2

Related Questions