4

단편화가 단 하나의 인스턴스 또는 싱글 톤을 가질 수 있습니까?
Google은 프로젝트도 iosched했습니다. 그들은 단순히 ... 그들이 원하는 때마다 단 하나의 인스턴스만으로 단편을 만들 수 있습니까?

Fragment a = new Fragment(); 

을 만들

한다고 가정 예 :

public static FragmentManager instance; 

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

    public TestFragment getTestFragment() { 
     if (testFragment == null) { 
      testFragment = new TestFragment(); 
     } 

     return testFragment 
    } 
} 

내가 거래 사방 FragmentManager.getInstance().getTestFragment() 사용할 수 있습니까?

예 :

getSupportFragmentManager() 
    .beginTransaction() 
    .replace(R.id.content_frame, FragmentManager.getInstance().getTestFragment()) 
    .commit(); 

또는 OS가 자동으로 참조 또는 이와 관련된 몇 가지 문제를 파괴?

답변

3

getSupportFragmentManager().beginTransaction().replace을 사용할 때 세 번째 매개 변수를 태그로 사용할 수있는 문자열로 추가 할 수 있으므로 이전 조각을 복구하려는 경우 getSupportFragmentManager().findFragmentByTag(String)을 사용할 수 있으므로 새 조각을 만들 필요가 없습니다 . 조각이 findFragmentByTag(String)를 사용하여 존재하는 경우

그래서 그것은하지 존재하는 경우, 새로운 단편을 만들고 myTag 당신이 당신의 findFragmentByTag에 사용합니다 문자열이 어디 getSupportFragmentManager().beginTransaction() .replace(R.id.content_frame,myFragment,myTag).commit();를 호출이

확인 같은 것입니다. 이렇게하면 모든 유형의 조각을 하나 이상 만들 수 없습니다.

나는 그것이 어떤 의미 : 자세한 내용은

thisthis

2

이러한 제한을 확인할 수 있기를 바랍니다. 그러나 두 조각 객체는 동일한 태그 또는 ID를 가져서는 안됩니다.

또한 기존 조각을 다시 첨부하는 것이 좋으며 새로운 조각을 만드는 것이 좋습니다. 당신이 추가 또는 두 번 이상 동일한 "유형"과의 조각 중 하나 이상을 대체하지 않습니다 있는지 확인하려는 경우

MyFragment f = (MyFragment) getFragmentManager().findFragmenByTag("my_fragment"); 

if(f == null){ 
    f = Fragment.instantiate(context, MyFragment.class.getName()); 
} 

if(!f.isAdded()){ 
    //--do a fragment transaction to add fragment to activity, WITH UNIQUE TAG-- 
    //--Optionally, add this transaction to back-stack as well-- 
} 
0

는 당신은 당신의 조각을 알고하는 FragmentManager.BackStackEntry을 사용할 수 있습니다 현재 스택 맨 위에 있습니다.

String TAG_FIRST_FRAGMENT = "com.example.name.FIRST.tag"; 
String TAG_SECOND_FRAGMENT = "com.example.name.SECOND.tag"; 

FragmentManager fragmentManager = getSupportFragmentManager(); 
if (fragmentManager.getBackStackEntryCount() == 0 || 
    !fragmentManager.getBackStackEntryAt(
     fragmentManager.getBackStackEntryCount() - 1) 
    .getName().equals(TAG_SECOND_FRAGMENT)) { 
//Now it's safe to add the secondFragment instance 

FragmentTransaction transaction = fragmentManager.beginTransaction(); 
//Hide the first fragment if you're sure this is the one on top of the stack 
transaction.hide(getSupportFragmentManager().findFragmentByTag(TAG_FIRST_FRAGMENT)); 
SecondFragment secondFragment = new SecondFragment(); 
transaction.add(R.id.content_frame, secondFragment, TAG_SECOND_FRAGMENT); 
//Add it to back stack so that you can press back once to return to the FirstFragment, and 
//to make sure not to add it more than once. 
transaction.addToBackStack(TAG_SECOND_FRAGMENT); 
transaction.commit(); 

} 
관련 문제