可以用片段只有一个实例被创建 [英] Can fragment be created with only one instance
问题描述
我只是想知道,可以片断创建只有一个实例或单身?结果
我通过的谷歌iosched 的项目做得太过分。他们只需创建
I was just wondering, can fragment creation only have one instance or singleton?
I went through Google iosched project too. They simply create
Fragment a = new Fragment();
每当他们想...
Whenever they want...
假设例如:
public static FragmentManager instance;
public static FragmentManager getInstance() {
if (instance == null) {
instance = new FragmentManager();
}
return instance;
}
public TestFragment getTestFragment() {
if (testFragment == null) {
testFragment = new TestFragment ();
}
return testFragment
}
}
我可以使用随处可见 FragmentManager.getInstance()。getTestFragment()
事务?
例如:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.content_frame, FragmentManager.getInstance().getTestFragment())
.commit();
或操作系统自动销毁引用或与之相关的一些问题?
Or OS automatically destroy the reference or some issues related to it?
推荐答案
当您使用 getSupportFragmentManager()调用BeginTransaction()代替
您可以添加第三个参数作为字符串,可以作为一个标签,这样的情况下,要恢复你可以使用previous片段使用, getSupportFragmentManager()。findFragmentByTag(字符串)
让你赢了不用为了创建一个新的片段。
When you use getSupportFragmentManager().beginTransaction().replace
you can add a third parameter as a string that you can use as a tag, so in case you want to recover a previous fragment you can use getSupportFragmentManager().findFragmentByTag(String)
so you won't have to create a new fragment.
因此,它会是这样
检查是否存在片段使用 findFragmentByTag(字符串)
如果不存在的话,创建一个新的片段,并调用 getSupportFragmentManager()调用BeginTransaction() .replace(R.id.content_frame,myFragment,MyTag的).commit();
其中MyTag的是你在你的findFragmentByTag使用的字符串。这样,你就不会创建的每一个类型的多个片段。
Check if the fragment exists using findFragmentByTag(String)
if it not exists, create a new fragment and call getSupportFragmentManager().beginTransaction() .replace(R.id.content_frame,myFragment,myTag).commit();
where myTag is the String you'll use in your findFragmentByTag. This way you won't create more than one fragment of every type.
我希望这是有道理的:)
I hope it makes some sense :)
有关详细信息,检查<一href=\"http://developer.android.com/reference/android/app/FragmentTransaction.html#replace%28int,%20android.app.Fragment,%20java.lang.String%29\"相对=nofollow>这个和<一个href=\"http://developer.android.com/reference/android/app/FragmentManager.html#findFragmentByTag%28java.lang.String%29\"相对=nofollow>这个
For more information check this and this
这篇关于可以用片段只有一个实例被创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!