使用片段标记 [英] Uses of fragment tags
问题描述
在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 之前创建code>与标记,它现在可以从
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:
<一个href="http://stackoverflow.com/questions/7951730/viewpager-and-fragments-whats-the-right-way-to-store-fragments-state">ViewPager和片段 - 什么是正确的方式来存储片段的状态
这篇关于使用片段标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!