16

Pytanie ogólne Czy mogę zdefiniować fragmenty jako Singletony?Fragment jako singleton w Androidzie

konkretne pytanie W mojej aplikacji mam jedno „FragmentActivity” z FragmentPager który ma dwa fragmenty FragmentA i FragmentB.

zdefiniowałem fragmenty jak singletons w FragmentA rozciąga Fragment Klasa:

private static instance = null; 

public static FragmentA getInstance() { 
    if (instance == null) { 
     instance = new FragmentA(); 
    } 
    return instance; 
} 
private FragmentA() {} 

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

i to jak ja nadmuchać fragmenty układ:

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

Mój problem:

Po pierwszym uruchomieniu aplikacji wszystko działa poprawnie. Po zamknięciu aplikacji, a następnie uruchomieniu jej ponownie, nie widzę obu fragmentów.

+0

co to jest prywatna instancja statyczna? Wierzę, że to błąd hehe .. Mine działa dobrze – Sheychan

Odpowiedz

23

Fragmenty mają być wielokrotnymi składnikami aplikacji. Nie powinieneś używać ich jako singletonów, zamiast tego powinieneś zaimplementować Fragment.SavedState lub 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 
    } 
} 
+0

czy możesz wyjaśnić? –

+0

Oczywiście, będę edytować moją odpowiedź. – hwrdprkns

+0

Początkowo chciałem to zrobić, ponieważ moje fragmenty są zawsze widoczne, a obsługuję tylko orientację pionową. –