Uses of fragment tags

后端 未结 2 1147
感情败类
感情败类 2020-12-25 12:20

In Android, you can set a tag for a Fragment in a FragmentTransaction.

Why would I need to set a tag for a Fragment?

And is it good practice if a Fragment ch

2条回答
  •  生来不讨喜
    2020-12-25 12:23

    Fragment tags can be used to avoid recreating a Fragment on Activity orientation change.

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photos_image_pager);
    
        MyFragment fragment;
        if (savedInstanceState != null) {
            fragment = (MyFragment) getFragmentManager()
                .findFragmentByTag("my_fragment_tag");
        } else {
            fragment = new MyFragment();
            fragment.setArguments(getIntent().getExtras());
            getFragmentManager()
                .beginTransaction()
                .add(android.R.id.content, fragment, "my_fragment_tag")
                .commit(); 
        }
    }
    

    The Activity is recreated on orientation change, and its onCreate(...) method is called. If the Fragment was created before the Activity was destroyed and was added to the FragmentManager with a tag, it can now be retrieved from the FragmentManager by the same tag.

    For a longer discussion on how it can be used, see:

    • ViewPager and fragments - what's the right way to store fragment's state?

提交回复
热议问题