Search code examples
androidandroid-listfragment

Do we need to use Fragment Tag for Fragments in Android


I am using a ListFragment and a Detail Fragment. The example from Android Studio uses tag for the list view. But i already have a ListView in a LinearLayout. can i use that or should it have a fragment tag. If not, then what is the advantage of using fragment tag.


Solution

  • When you use <fragment ..> tag in xml layout of your Activity, your Fragment is automatically committed by FragmentManager, but you should either specify a tag (which is a String) or id (which is primitive int) when declaring it:

    <fragment android:id="@+id/my_fragment" ...>

    or

    <fragment android:tag="mytag" ..>

    Fragment must have an unique identifier so that it can be re-associated with a previous instance upon Activity recreation (on configuration change, resuming after pressing home button, etc).

    For example, it is useful to have an id or tag when performing calls to:

    FragmentManager.findFragmentByTag(String tag);

    FragmentManager.findFragmentById(int id);//fragment id or its container id