How do you supply construction arguments into a Fragment?

Asked 10-Jan-2018
Viewed 1224 times

1

How do you supply construction arguments into a Fragment?


1 Answer


0

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;

    }