How to set a Tag to a Fragment in Android
Asked Answered
R

2

13

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?

Rosina answered 5/5, 2015 at 19:57 Comment(0)
B
26

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

Bassett answered 5/5, 2015 at 20:1 Comment(0)
O
0

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 );
        }
Opinicus answered 5/5, 2015 at 20:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.