0
votes

I have 3 tabs in viewpager. Lets call them tab A,B,C. Each of the tabs have their own fragments, lets call them frag1, frag2, frag3. I want to replace frag1 in tab A with a new fragment frag4 and leave the other tabs in viewpager untouched. I have tried replacing the fragment but it doesnt work. Do i need to implement something in my pageradapter ?

public class SectionsPagerAdapter extends FragmentPagerAdapter {

private FragmentManager mFragmentManager;
private Fragment frag = null;

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


public void onSwitchToNextFragment() {
    mFragmentManager.beginTransaction().remove(frag)
            .commit();
    if (frag instanceof Fragment1){

        Log.v("here","swapping");
        frag = Fragment4.newInstance();
    }
    Log.v("here","notified");
    notifyDataSetChanged();
}
@Override
public Fragment getItem(int position) {
    switch (position) {
        case 0:
            frag = Fragment1.newInstance();
            Log.v("here","in getitem");
            return frag;

        default:
            Log.v("here","in default");
            return Fragment2.newInstance();
    }
}

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

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

public void switchFrag(){
      onSwitchToNextFragment();
    //    mFragmentManager.beginTransaction().replace(R.id.container,frag).commit();
    //        mFragmentManager.beginTransaction().add(frag).commit();
    notifyDataSetChanged();
}
1

1 Answers

0
votes

There are two ways to replace a fragment in a viewpager. Option one: Override the getItemPosition(Object object) method.

public int getItemPosition(Object object) {
    return POSITION_NONE;
}

When you call notifyDataSetChanged(), the view pager will remove all views and reload them all. But this is not very efficient.

Or you call instantiateItem() when instantiating a new view. Then instead of using notifyDataSetChanged(), you can use findViewWithTag() to find the view you want to update. This option is more efficient and flexible