2017-12-16 4 views
0

ViewPager에서 프래그먼트를 바꾸려고하는데 가장 좋은 방법은 없습니다. R.id.root_frame 내가 대체 할 단편의 용기이며, 그것은 FrameLayout이있다ViewPager에서 프래그먼트를 바꿉니다. 이전 조각은 제거되지 않습니다.

Fragment productDetailFragment = RetarFragment.newInstance(null, null); 
    FragmentTransaction transaction = getChildFragmentManager().beginTransaction(); 
    transaction.replace(R.id.root_frame, productDetailFragment).commit(); 

:이 코드를 사용하여 단편을 변경하기 위해

.

문제는 앱을 실행할 때 조각이 잘 실행되지만 이전 조각이 제거되어야한다는 것입니다.

더 좋은 해결책이 있습니까?

ViewPager의 어댑터는 고유의 태그와 함께 조각을 추가 할 MEED FragmentStatePagerAdapter

public class SectionsPagerAdapter extends FragmentStatePagerAdapter implements Serializable{ 


    public static final int MENU_RETAR = 2; 
    public static final int MENU_BATALLA = 1; 
    int MENU_ACTUAL = MENU_BATALLA; 

    public SectionsPagerAdapter(FragmentManager fm) { 
     super(fm); 
    } 

    @Override 
    public Fragment getItem(int position) { 
     // getItem is called to instantiate the fragment for the given page. 
     // Return a PlaceholderFragment (defined as a static inner class below). 
     switch (position){ 
      case 0: return new TimelineFragment(); 
      case 1: return new SearchFragment(); 
      case 2: 

       if(MENU_ACTUAL == MENU_RETAR){ 
        return new RetarFragment(); 
       }else{ 
        return new MenuBatallaFragment(); 
       } 

      case 3: return new NotificacionesFragment(); 
      case 4: return new PerfilFragment().newInstance(this); 
      default: 
       return new TimelineFragment(); 
     } 
    } 



    @Override 
    public int getItemPosition(Object object) { 

     return POSITION_NONE; 
    } 

    @Override 
    public int getCount() { 
     // Show 3 total pages. 
     return 5; 
    } 

    @Override 
    public CharSequence getPageTitle(int position) { 
     switch (position) { 
      case 0: 
       return null; 
      case 1: 
       return null; 
      case 2: 
       return null; 
      case 3: 
       return null; 
      case 4: 
       return null; 
     } 
     return null; 
    } 
} 

답변

0

처음이다. 그런 다음 오래된 조각을 제거하려면 교체 할 때마다 고유 한 조각 태그가있는 조각을 제거해야합니다.

조각 제거;

Fragment fragment =getSupportFragmentManager().findFragmentByTag(TAG); 

if(fragment != null) 
    getSupportFragmentManager().beginTransaction().remove(fragment).commit(); 
+0

좋아요,하지만 ... 조각을 지울 때? –

+0

교체하기 전에 조각을 제거하면 결과 조각이 비어 있습니다. –

0

는 새로운 조각의 레이아웃에 배경 = "true"를 클릭 그것은 바로 실행을 설정하면

해결!

관련 문제