片段作为Android中的单身人士

时间:2013-02-12 18:21:53

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

一般问题 我可以将碎片定义为单身人士吗?

具体问题 在我的应用程序中,我有一个'FragmentActivity',FragmentPager有两个片段,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;
}

我的问题:

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

1 个答案:

答案 0 :(得分:26)

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