Fragment as a singleton in Android(片段作为 Android 中的单例)
问题描述
一般问题我可以将片段定义为单例吗?
General Question Can I define Fragments as Singletons?
具体问题在我的应用程序中,我有一个带有 FragmentPager
的FragmentActivity",它有两个片段,FragmentA
和 FragmentB
.
Specific question
In my application I have one 'FragmentActivity' with a FragmentPager
which has two Fragments, FragmentA
and FragmentB
.
我在 FragmentA
extends Fragment
类中将片段定义为单例:
I defined the fragments as Singletons in the FragmentA
extends Fragment
class:
private static instance = null;
public static FragmentA getInstance() {
if (instance == null) {
instance = new FragmentA();
}
return instance;
}
private FragmentA() {}
在我的 FragmentPagerAdapter
中:
@Override
public Fragment getItem(int position) {
switch(position){
Fragment fragment = null;
case 0:
fragment = FragmentA.getInstance();
break;
case 1:
fragment = FragmentB.getInstance();
break;
}
return fragment;
}
这就是我膨胀片段布局的方式:
and this is how I inflate the fragments layout:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
fragmentView = (RelativeLayout) inflater.inflate(R.layout.fragment_a_layout, container, false);
return fragmentView;
}
我的问题:
当我第一次启动我的应用程序时,一切正常.当我关闭我的应用然后重新启动它时,我没有看到这两个片段.
When I first launch my app everything works well. When I close my app and then restart it, I'm not seeing both of the fragments.
推荐答案
片段是应用程序的可重用组件.您不应该将它们用作单例,而应该实现 Fragment.SavedState 或 onSavedInstanceState.
Fragments are meant to be reusable components of applications. You should not be using them as singletons, instead you should implement Fragment.SavedState or onSavedInstanceState.
public class YourFragment extends Fragment {
// Blah blah blah you have a lot of other code in this fragment
// but here is how to save state
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// savedInstanceState will have whatever you left in the outState bundle above
}
}
这篇关于片段作为 Android 中的单例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:片段作为 Android 中的单例
基础教程推荐
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01