Uses of fragment tags

android, android-fragments, java, kotlin

Solution

Fragment tags can be used to avoid recreating a `Fragment` on `Activity` orientation change.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.photos_image_pager);

    MyFragment fragment;
    if (savedInstanceState != null) {
        fragment = (MyFragment) getFragmentManager()
            .findFragmentByTag("my_fragment_tag");
    } else {
        fragment = new MyFragment();
        fragment.setArguments(getIntent().getExtras());
        getFragmentManager()
            .beginTransaction()
            .add(android.R.id.content, fragment, "my_fragment_tag")
            .commit(); 
    }
}

The `Activity` is recreated on orientation change, and its `onCreate(...)` method is called. If the `Fragment` was created before the `Activity` was destroyed and was added to the `FragmentManager` with a tag, it can now be retrieved from the `FragmentManager` by the same tag.

For a longer discussion on how it can be used, see:

- ViewPager and fragments - what's the right way to store fragment's state?

Problem

In Android, you can set a tag for a Fragment in a FragmentTransaction. Why would I need to set a tag for a Fragment? And is it good practice if a Fragment changed its behavior based on its tag?

Original source

Related problems