我的应用程序中只有一项 Activity ,其中有 4 个 fragment ,这些 fragment 在底部选项卡菜单中切换。所以每次它总是屏幕上的 4 个 fragment 之一。看起来很简单,但我在问自己,为什么通过切换Fragment,每次都必须重新创建新的Fragment对象?这是来自 android 文档:
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Replace the contents of the container with the new fragment
ft.replace(R.id.your_placeholder, new FooFragment());
// or ft.add(R.id.your_placeholder, new FooFragment());
// Complete the changes added above
ft.commit();
我可以尝试自己存储对 fragment 的引用,并每次选择准备好的对象,但我发现了这种 fragment 使用风格的示例,所以它可能有问题?
最佳答案
一次创建所有 fragment 并使用它或将 fragment 对象作为单例来制作它。
单例示例:
class MyFragment extends Fragment{
private static MyFragment instance;
public static MyFragment getInstance(){
if(instance == null)
instance = new MyFragment();
return instance;
}
}
使用MyFragment.getInstance();创建对象 fragment
现在它不会每次都创建新的对象。
关于android - 如何避免每次通过切换fragment来创建Fragment对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46204482/