Setting fragments by tag

76 views Asked by At

How do I go about setting my Fragments by tag since I did not explicitly make them in my XML so I can't use findbyID.

I have 4 Fragments in an Activity and want to pass data back and forth from the Fragments but I keep getting error

Attempt to invoke virtual method 'void com.project.myproject.app.Fragment.addToList()' on a null object reference

I don't think I am setting my Fragment's tags right so could someone please link me to an example of this?

1

There are 1 answers

1
Ellie Zou On

Set the tag for fragment:

YourFragment fragment = getFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment, fragment, "YOUR_TAG").addToBackStack("YOUR_TAG").commit();

Get the fragment:

private YourFragment getFragment() {
    YourFragment fragment = getSupportFragmentManager().findFragmentByTag("YOUR_TAG");
    if (fragment == null) {
        fragment = new YourFragment();
    }
    return fragment;
}