Damia Fuentess Damia Fuentess - 6 months ago 119
Android Question

Fragments inheritance with newInstance pattern

Which is the correct way to make fragments inheritance with newInstance pattern?

For example, if we have a fragment MyFragment that inherits from another fragment SuperFragment which has the newInstance pattern --> http://stackoverflow.com/a/28855715/5125212

public class SuperFragment extends Fragment{
public static SuperFragment newInstance(int var1, boolean var2){
SuperFragment fragment = new SuperFragment();
Bundle b = new Bundle();
b.putInt("my_var1", var1);
b.putBoolean("my_var2", var2);
fragment.setArguements(b);
return fragment
}
// All other methods
}


This gets an error on "super":

public class MyFragment extends SuperFragment{
public static MyFragment newInstance(int var1, boolean var2){
return super.newInstance(int var1, var2);
}
// All other methods
}


And this gets an error on constructor as we should avoid non-default constructors:

public class MyFragment extends SuperFragment{
public MyFragment(int var1, boolean var2){
newInstance(var1, var2);
}
// All other methods
}


And I found this to don't have any error but I don't like it because it semms to get recursively:

public class MyFragment extends SuperFragment{
public static SuperFragment newInstance(int var1, boolean var2){
return newInstance(var1,var2);
}
}

Answer

Find it!

Super fragment:

public class SuperFragment extends Fragment{
    public static Bundle setArgs(int var1, boolean var2){
        Bundle b = new Bundle();
        b.putInt("my_var1", var1);
        b.putBoolean("my_var2", var2);
        return b;
    }
// All methods you want in the super fragment, so they will be in the 
// inherit fragment too
}

Inherit fragment:

public class MyFragment extends SuperFragment{
    public static MyFragment newInstance(int var1, boolean var2){
        SuperFragment fragment = new SuperFragment();
        fragment.setArguments(setArgs(var1,var2));
        return fragment;
    }
// All other methods that you only want them on the inherit (this)     
// fragment
}