0

Is it possible to have two different constructors for the same Fragment ?

Here's my case : I have Fragment_A and Fragment_B which are almost identically, except one gets an Integer and the other a String.

Can I have something like this :

public static VideoListFragment newInstanceA(String filterString) {
    VideoListFragment myFragment = new VideoListFragment();

    Bundle args = new Bundle();
    args.putString(FILTER, filterString);
    myFragment.setArguments(args);

    return myFragment;
}

public static VideoListFragment newInstanceB(String subjectId) {
    VideoListFragment myFragment = new VideoListFragment();

    Bundle args = new Bundle();
    args.putString(POSITION, subjectId);
    myFragment.setArguments(args);

    return myFragment;
}

If this is possible then how am I going to get in onCreate() the argument ? I have somehow to check if getArguments()` contains FILTER String or POSITION Integer.

Mes
  • 1,671
  • 3
  • 20
  • 36

2 Answers2

3

You cannot use an exact same method signature to distinguish between different input behaviors. However, you can extend input parameters to make it more versatile. Something like this would help:

public class VideoListFragment extends Fragment {    
    public static VideoListFragment newInstance(String type, String val) {
        VideoListFragment myFragment = new VideoListFragment();

        Bundle args = new Bundle();
        args.putString(type, val);
        myFragment.setArguments(args);

        return myFragment;
    }
}

and later use it as below:

VideoListFragment frag1 = VideoListFragment.newInstance(FILTER, "value");  //for Filter
VideoListFragment frag2 = VideoListFragment.newInstance(POSITION, "value");//for Position
waqaslam
  • 67,549
  • 16
  • 165
  • 178
  • But I have different names : `newInstanceA` and `newInstanceB` . Will it work like this? Otherwise, your answer is a good alternative option for me. – Mes May 19 '16 at 05:08
  • 1
    Yes, if you provide separate names then it will work, but that is unnecessary redundancy for such a minor thing to achieve. – waqaslam May 19 '16 at 09:09
0

Android docs discourages the use of constructors while working with fragments; you should use bundle instead.