How do you supply construction arguments into a Fragment?

1 votes
224 views
Harsh kumar srivastava asked 10-Jan-2018 in Technology by Harsh kumar srivastava

How do you supply construction arguments into a Fragment?

1 Answer

0 votes
Prateek sharma answered 10-Jan-2018 by Prateek sharma

there are several ways to instantiate and pass the data to the fragments. these methods should be taken care of while using them. the recommended way is to use factory methods to do that.

it is also important to take care of how the data is passed to the fragments. if the values are passed directly to the fragments and when the app is moved to the background then to give space to other application the memory will be freed and the values will be deleted to free the space.

the better ways to do it is by using the bundle to pass the arguments to the fragments. the below code illustrates this phenomenon - 

public static MyFragment newInstance(String name, int age) {

        Bundle bundle = new Bundle();

        bundle.putString("name", name);

        bundle.putInt("age", age);

        MyFragment fragment = new MyFragment();

        fragment.setArguments(bundle);

        return fragment;

    }