使用片段标记片段、标记

2023-09-05 00:18:13 作者:期待完美的自己

在Android中,你可以设置标签在FragmentTransaction一个片段。

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 changed its behavior based on its tag?

推荐答案

它可以用来避免重新创建一个片段活动取向的变化。

It can be used to avoid re-creating 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(); 
    }
}

活动的是方向变化重新创建,它的的onCreate(...)方法被调用。如果片段活动被摧毁,被添加到 FragmentManager 与标记,它现在可以从 FragmentManager 检索相同的标签。

The Activity is re-created on orientation change, and it's 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和片段 - 什么是正确的方式来存储片段的状态