amaroqz
amaroqz

Reputation: 73

FragmentTransaction with FragmentPagerAdapter

Im using a FragmentPagerAdapter to manage 3 Fragments.

public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        Fragment fragment = new Fragment();
        switch (position) {
            case 0:
                return fragment = new Latest();
            case 1:
                return fragment = new MySets();
            case 2:
                return fragment = new MyPictures();
            default:
                break;
        }
        return fragment;
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        //SET TITLE OF TABS
        Locale l = Locale.getDefault();
        switch (position) {
            case 0:
                return getString(R.string.title_section1_latest).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2_mysets).toUpperCase(l);
            case 2:
                return getString(R.string.title_section3_allpictures).toUpperCase(l);
        }
        return null;
    }
}

All Fragements extend Fragment. To handle Click Events and a Custom Layout Im using a Adapter which extends BaseAdapter. My Goal is to replace Fragment 2 through another Fragment. Is it correct that I have to add all Fragments with FragmentTransaction to replace them later?

But how can i dynamically add the fragments to use FragmentTransaction? Is there a way to add them at the getItem(int position) or is that the wrong way to go?

Upvotes: 1

Views: 1634

Answers (1)

AndroidEnthusiast
AndroidEnthusiast

Reputation: 6657

Edit

If you need the Fragment as soon as the app is launched then the approach you used above in getItem() is okay, you don't need to do the transaction from there.

If you want to replace the Fragment later on simply use the getSupportFragmentManger and a transaction in the Fragment.

            NewFragment newFrag = new NewFragment();
    FragmentTransaction transaction = getActivity()
            .getSupportFragmentManager().beginTransaction();
    transaction.replace(R.id.your_fragment_container_id, newFrag);
    transaction.addToBackStack(null);
    transaction.commit();

Upvotes: 0

Related Questions