Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a Tag to a Fragment in Android

I've looked at all the questions on Stackoverflow but could not find a single definitive answer to this question. How do you set a Tag to a Fragment so that you can retrieve it via getFragmentManager().findFragmentByTag()? Could someone give a simple code example of how to create a tag to a Fragment?

like image 888
CBA110 Avatar asked May 05 '15 19:05

CBA110


People also ask

What is the use of fragment tag in Android?

A Fragment represents a reusable portion of your app's UI. A fragment defines and manages its own layout, has its own lifecycle, and can handle its own input events. Fragments cannot live on their own--they must be hosted by an activity or another fragment.

How do I attach a fragment to an activity?

Add a fragment to an activity You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.

How do I attach a fragment to an activity Kotlin?

We can use the getSupportFragmentManager() method to get a fragment manager. FragmentTransaction. add(): This method is used to add a fragment to the activity. addToBackStack(): This method is used to add a transaction to the back stack.


1 Answers

You can set a Tag during fragment transaction.

For example if it's a replace transaction you could do it like so:

FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
        .replace(R.id.fragment_container, mFragment, TAG)
        .commit();

If the Fragment you're using is not from Support Library, use getFragmentManager() instead of getSupportFragmentManager().

like image 178
Bartek Lipinski Avatar answered Oct 27 '22 12:10

Bartek Lipinski