0

I'm quoting Google's documentation:

All subclasses of Fragment must include a public empty constructor. The framework will often re-instantiate a fragment class when needed, in particular during state restore, and needs to be able to find this constructor to instantiate it.

What happens if a Fragment needs parameters? Say I created an instance of the fragment using a non-parameterless c'tor and then added the fragment to an Activity. How would Android know what to upon state restoration? Or am I supposed to manually take care of it (which I probably can't if the parameter was for instance a complex view model)?

Krumelur
  • 32,180
  • 27
  • 124
  • 263
  • The other thread doesn't really answer how to deal with complex parameters like a view model that cannot be serialized and is created be the owning activity. – Krumelur Jan 29 '14 at 13:41
  • You should mention it in your question that your model cannot be serialized. By the way, what kind of data do you have to pass? – fasteque Jan 29 '14 at 13:45
  • @fasteque I thought I did. See last sentence. But what is the solution if the parameter cannot be serialized? – Krumelur Jan 29 '14 at 13:59
  • You can set a Parcelable object in the bundle, you can refer to this link to understand how to write a custom class: http://developer.android.com/reference/android/os/Parcelable.html – fasteque Jan 29 '14 at 14:16

1 Answers1

1

You need to pass it a Bundle with the parameters, like so:

class MyFragment extends Fragment{
   private static final String MY_FIELD = "myfield";


    public static MyFragment newInstance(int param){
        MyFragment result = new MyFragment();
        Bundle args = new Bundle();
        args.putInt(MY_FIELD, param);
        result.setArguments(args);
        return result;
    }


    ...


    private void myMethod(){
        int myField = getArguments.getInt(MY_FIELD);

    }

}
Toon Borgers
  • 3,638
  • 1
  • 14
  • 22