[android] How to set a Fragment tag by code?

I haven't found something like setTag(String tagName) method in the Fragment class. The only way to set a Fragment tag that I have found is by doing a FragmentTransaction and passing a tag name as parameter.

Is this the only way to explicitly set a Fragment tag by code?

This question is related to android android-3.0-honeycomb android-fragments

The answer is


Nowadays there's a simpler way to achieve this if you are using a DialogFragment (not a Fragment):

val yourDialogFragment = YourDialogFragment()
yourDialogFragment.show(
    activity.supportFragmentManager,
    "YOUR_TAG_FRAGMENT"
)

Under the hood, the show() method does create a FragmentTransaction and adds the tag by using the add() method. But it's much more convenient to use the show() method in my opinion.

You could shorten it for Fragment too, by using a Kotlin Extension :)


You can set tag to fragment in this way:

Fragment fragmentA = new FragmentA();
getFragmentManager().beginTransaction()
    .replace(R.id.MainFrameLayout,fragmentA,"YOUR_TARGET_FRAGMENT_TAG")
    .addToBackStack("YOUR_SOURCE_FRAGMENT_TAG").commit(); 

You can provide a tag inside your activity layout xml file.

Supply the android:tag attribute with a unique string.

Just as you would assign an id in a layout xml.

    android:tag="unique_tag"

link to developer guide


You can also get all fragments like this:

For v4 fragmets

List<Fragment> allFragments = getSupportFragmentManager().getFragments();

For app.fragment

List<Fragment> allFragments = getFragmentManager().getFragments();

I know it's been 6 years ago but if anyone is facing the same problem do like I've done:

Create a custom Fragment Class with a tag field:

public class MyFragment extends Fragment {
 private String _myTag;
 public void setMyTag(String value)
 {
   if("".equals(value))
     return;
   _myTag = value;
 }
 //other code goes here
}

Before adding the fragment to the sectionPagerAdapter set the tag just like that:

 MyFragment mfrag= new MyFragment();
 mfrag.setMyTag("TAG_GOES_HERE");
 sectionPagerAdapter.AddFragment(mfrag);

You can add the tag as a property for the Fragment arguments. It will be automatically restored if the fragment is destroyed and then recreated by the OS.

Example:-

    final Bundle args = new Bundle();
    args.putString("TAG", "my tag");
    fragment.setArguments(args);

This is the best way I have found :

   public class MainActivity extends AppCompatActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState == null) {
          // Let's first dynamically add a fragment into a frame container
          getSupportFragmentManager().beginTransaction(). 
              replace(R.id.flContainer, new DemoFragment(), "SOMETAG").
              commit();
          // Now later we can lookup the fragment by tag
          DemoFragment fragmentDemo = (DemoFragment) 
              getSupportFragmentManager().findFragmentByTag("SOMETAG");
        }
    }
}

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-3.0-honeycomb

Why fragments, and when to use fragments instead of activities? How to implement the Android ActionBar back button? How to hide action bar before activity is created, and then show it again? Android replace the current fragment with another fragment getActionBar() returns null Fragments onResume from back stack How to set a Fragment tag by code? Android: How to change the ActionBar "Home" Icon to be something other than the app icon? ActionBar text color Unable to resolve host "<insert URL here>" No address associated with hostname

Examples related to android-fragments

FragmentActivity to Fragment How to start Fragment from an Activity How to use data-binding with Fragment In android how to set navigation drawer header image and name programmatically in class file? Android Fragment onAttach() deprecated How to convert any Object to String? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments java.lang.IllegalStateException: Fragment not attached to Activity java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference