How to set a Fragment tag by code?

2019-01-10 17:52发布

问题:

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?

回答1:

Yes. So the only way is at transaction time, e.g. using add, replace, or as part of the layout.

I determined this through an examination of the compatibility sources as I briefly looked for similar at some point in the past.



回答2:

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


回答3:

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

"Supply the android:tag attribute with a unique string."

just as you assign id in a layout xml.

    android:tag="unique_tag"

link to developer guide



回答4:

You can also get all fragments like this:

For v4 fragmets

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

For app.fragment

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


回答5:

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);


回答6:

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");
    }
}

}



回答7:

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);