Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 --> https://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);
    }
}
like image 333
Damia Fuentes Avatar asked Feb 17 '26 01:02

Damia Fuentes


1 Answers

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){
        MyFragment fragment = new MyFragment();
        fragment.setArguments(setArgs(var1,var2));
        return fragment;
    }
// All other methods that you only want them on the inherit (this)     
// fragment
}
like image 102
Damia Fuentes Avatar answered Feb 18 '26 15:02

Damia Fuentes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!