3

I have always created fragments and passed my parameters to the fragment by using the newInstance() pattern. This works great for one or two parameters. I'm creating a fragment now that has around 10 parameters, and all of them are optional.

I was thinking about using the Builder pattern, similar to how the AlertDialog works. However, I'm not exactly sure what would be the best way to implement this, or if it is even a good idea.

Here is an example of what I was thinking, but with many more variables.

public class MyFragment extends Fragment {
    private String name;

    private static class Builder {
        private String name;

        public Builder setName(String name) {
            this.name = name;
            return this;
        }

        public MyFragment build() {
            return new MyFragment(this);
        }
    }

    // NOT ALLOWED
    public MyFragment(Builder builder) {
        name = builder.name;
    }
    // Rest of the fragment...
}

The problem with this is that the fragment must have a default constructor, so this will not work.

Is there a "correct" way to accomplish this?

Mark
  • 1,130
  • 3
  • 17
  • 32

2 Answers2

6

In your Builder's build() you could do something like:

public MyFragment build() {
     MyFragment fragment = new MyFragment();
     Bundle bundle = new Bundle();
     bundle.put(ARG_1_TAG, this.arg1);
     ...
     fragment.setArguments(bundle);
     return fragment;
}

This has the advantage of providing your instance with your arguments set, but eliminates the need for an additional newInstance() method.

emerssso
  • 2,376
  • 18
  • 24
2

You should leave public empty constructor.

Sample of the builder:

public class MyFragment extends Fragment {

    private String name;

    public static class Builder {
        private final Bundle arguments;

        public Builder() {
            arguments = new Bundle();
        }

        public Builder setName(String name) {
            arguments.putString("name", name);
            return this;
        }

        public MyFragment build() {
            MyFragment fragment = new MyFragment();
            fragment.setArguments(arguments);
            return fragment;
        }
    }

    public MyFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        name = getArguments().getString("name");
    }
}
ls.illarionov
  • 741
  • 1
  • 10
  • 12