CBA110
CBA110

Reputation: 1092

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?

Upvotes: 14

Views: 29254

Answers (2)

Bartek Lipinski
Bartek Lipinski

Reputation: 31458

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().

Upvotes: 27

Olkunmustafa
Olkunmustafa

Reputation: 3203

I used that feature to provide between Dialog box and Fragment. When a alteration is made in Dialogbox, App can easily update Fragment UI

MyFragment.

DialogFragment dialog = LastCycleDate.newInstance( last_period_start );
        dialog.setTargetFragment( this, 0 );
        dialog.show( getActivity().getSupportFragmentManager(), "showLastCycleDate" );

MyDailogBox.java

Fragment targetFragment; = getTargetFragment();
if( targetFragment instanceof IntroParentFragment ){
            IntroParentFragment introParentFragment = ( IntroParentFragment ) targetFragment;
            introParentFragment.mutualMethods.setLastCycleStartDay( start_date );
        }

Upvotes: 0

Related Questions