Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragment newInstance why use arguments?

What is the real difference between these two approaches?

1.I am using standard old-fashined bundle:

    public static final Fragment newInstance(int val1, int val2) {
    TestFragment f = new TestFragment();
    Bundle bundle = new Bundle();
    bundle.putInt("val1", val1);
    bundle.putInt("val2", val2);
    f.setArguments(bundle);
    return f;
}

2.I am setting as instance members

    public static final Fragment newInstance(int val1, int val2) {
    TestFragment f = new TestFragment();
    f.val1 = val1;
    f.val2 = val2;
    return f;
}
like image 321
Heisenberg Avatar asked Apr 19 '16 11:04

Heisenberg


People also ask

What is the purpose of using fragments in an activity?

Fragments introduce modularity and reusability into your activity's UI by allowing you to divide the UI into discrete chunks. Activities are an ideal place to put global elements around your app's user interface, such as a navigation drawer.

Why is it recommended to use only the default constructor to create a fragment?

Traditionally, a Fragment instance could only be instantiated using its default empty constructor. This is because the system would need to reinitialize it under certain circumstances like configuration changes and the app's process recreation.

Can I use onCreate in fragment?

Fragment has many methods which can be overridden to plug into the lifecycle (similar to an Activity): onAttach() is called when a fragment is connected to an activity. onCreate() is called to do initial creation of the fragment. onCreateView() is called by Android once the Fragment should inflate a view.


2 Answers

In the first example, you've not actually set the fragment instance variables val1 and val2, so they remain uninitialized. Because of this, you'd be required to read back the bundle in onCreate to set the instance variables.

When the fragment instance is destroyed and re-created (e.g. due to a device rotation), the onCreate (or onCreateDialog for DialogFragments) can re-load the arguments using:

public void onCreate(Bundle savedInstanceState)
{
 if (savedInstanceState != null)
 {
  Bundle args = getArguments();
  val1 = args.getInt("val1");
  val2 = args.getInt("val2");
 }
}

and your state can be restored.

like image 185
CSmith Avatar answered Oct 20 '22 05:10

CSmith


The arguments bundle is retained along with the onSaveInstanceState(Bundle), while constructor parameters are not.

Similarly to what happens if you don't save out your fields to onSaveInstanceState() in an Activity. Think of the arguments bundle like an Intent, Intents are also retained across process death and configuration change.

like image 42
EpicPandaForce Avatar answered Oct 20 '22 05:10

EpicPandaForce