【问题标题】:Fragment as a singleton in Android片段作为 Android 中的单例
【发布时间】:2013-01-28 03:34:43
【问题描述】:

一般问题 我可以将片段定义为单例吗?

具体问题 在我的应用程序中,我有一个带有 FragmentPager 的“FragmentActivity”,它有两个片段,FragmentAFragmentB

我在FragmentA 扩展Fragment 类中将片段定义为单例:

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;
}

这就是我膨胀片段布局的方式:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    fragmentView = (RelativeLayout) inflater.inflate(R.layout.fragment_a_layout, container, false);
    return fragmentView;
}

我的问题:

当我第一次启动我的应用程序时,一切正常。 当我关闭我的应用然后重新启动它时,我没有看到这两个片段。

【问题讨论】:

  • 什么是私有静态实例?我相信这是一个错误,呵呵..我的工作正常

标签: android android-fragments android-viewpager android-fragmentactivity


【解决方案1】:

片段是应用程序的可重用组件。您不应该将它们用作单例,而应该实现 Fragment.SavedState 或 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
    }
}

【讨论】:

  • 我最初想这样做是因为我的片段始终可见,而且我只支持纵向。
  • 我仍然无法理解为什么当我关闭并重新启动它时它的行为会有所不同。当我的应用程序关闭时,碎片是否保持活动状态?
  • 片段可以在你的活动关闭时保持活动状态,但如果系统需要内存,它们也可以被回收。片段不保证始终存在。
  • 谢谢,所以如果我做对了,我最好只使用常规的 View Pager 和我的自定义视图而不是 Fragments?
  • 不,你最好使用 Fragments。 ViewPager 将以相同的方式被回收。片段更健壮,有点像 ViewControllers。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-29
  • 1970-01-01
  • 1970-01-01
  • 2017-04-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多