1
votes

In my app I have main Activity which implements a TabLayout which is switching between two fragments. They are handled like this:

private class PagerAdapter extends FragmentPagerAdapter {

        PagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return position == 0 ? Tab1Frag.getInstance()
                    : Tab2Frag.getInstance();
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return position == 0 ? "Tab1" : "Tab2";
        }
    }

They both (these fragments) implement from

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager

Otherwise I cannot use them in this manner.

All is working fine but now I face the issue. I want to sometimes change the Tab1 fragment with a different fragment with the following method:

private void replaceFragment(int code) { FragmentTransaction ft = getFragmentManager().beginTransaction();

    if(code==0){
        ViewListElementFrag fragment = new ViewListElementFrag ();
        ft.replace(R.id.fragmentFrame, fragment, ViewListElementFrag.TAG);
    }
    else if(code==1){
        EditElementFragment fragment = new EditElementFragment ();
        ft.replace(R.id.fragmentFrame, fragment, EditElementFragment.TAG);
    }
    ft.commit();
}

This is working fine normally, but now it is facing the issue.

FragmentTransaction ft = getFragmentManager().beginTransaction();

Is required to be appv4, but then it does not allow for replacing the fragments from standard android.app.fragment. How can I make it work, so my fragment from tab layout can be replaced by a different fragment? Or do I need to use new activity?

Thank you in advnace Grzegorz

EDIT:

To explain. In the line

 ft.replace(R.id.fragmentFrame, fragment, FragmentWhatever.TAG);

I get the error that the 2nd argument, fragment, should be of type android.suppotr.v4.app.Fragment

2

2 Answers

1
votes

You could also use this to replace a fragment

FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.fragmentFrame, fragment).commit();
1
votes

Instead of :

FragmentTransaction ft = getFragmentManager().beginTransaction();

use the Support library:

FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();

Also make sure to import:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;