[android] How can I access getSupportFragmentManager() in a fragment?

I have a FragmentActivity and I want to use a map fragment within it. I'm having a problem getting the support fragment manager to access it.

 if (googleMap == null) {
            googleMap = ((SupportMapFragment) getSupportFragmentManager()
                    .findFragmentById(R.id.map1)).getMap();

            // check if map is created successfully or not
            if (googleMap == null) {
                Toast.makeText(getApplicationContext(),
                        "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                        .show();
            }
        }

            // create marker
            MarkerOptions marker = new MarkerOptions().position(
                    new LatLng(latitude, longitude)).title("Hello Maps ");

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(new LatLng(latitude, longitude)).zoom(15).build();

            googleMap.animateCamera(CameraUpdateFactory
                    .newCameraPosition(cameraPosition));

            // adding marker
            googleMap.addMarker(marker);

The answer is


Simply get it like this -

getFragmentManager() // This will also give you the SupportFragmentManager or FragmentManager based on which Fragment class you have extended - android.support.v4.app.Fragment OR android.app.Fragment.

OR

getActivity().getSupportFragmentManager();

in your Fragment's onActivityCreated() method and any method that is being called after onActivityCreated().


do this in your fragment

getActivity().getSupportFragmentManager()

The simple new way of doing it in kotlin

requireActivity().supportFragmentManager

((AppCompatActivity) getActivity()).getSupportFragmentManager()

Some Kotlin code to use supportFragmentManager inside a Fragment.

  override fun onCreateView(
      inflater: LayoutInflater,
      container: ViewGroup?,
      savedInstanceState: Bundle?

  ): View? {

    super.onCreateView(inflater, container, savedInstanceState)
    val rootView = inflater.inflate(R.layout.fragment_home, container, false)

    // ....

    if (rootView.home_play_btn != null) {

      rootView.home_play_btn.setOnClickListener {
        val fragment: BaseFragment = ListFragment.newInstance()
        val fragManager: FragmentManager = (activity as AppCompatActivity).supportFragmentManager
        fragManager.beginTransaction()
            .replace(R.id.content_home_frame, fragment, TAG).commit()

      }

in java you can replace with

getChildFragmentManager()

in kotlin, make it simple by

childFragmentManager

hope it help :)


My Parent Activity extends AppCompatActivity so I had to cast my context to AppCompatActivity instead of just Activity.

eg.

FragmentAddProduct fragmentAddProduct = FragmentAddProduct.newInstance();
FragmentTransaction fragmentTransaction = ((AppCompatActivity)mcontext).getSupportFragmentManager().beginTransaction();

if you have this problem and are on api level 21+ do this:

   map = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map))
                    .getMap();

this will get the map when used inside of a fragment.


getFragmentManager() has been deprecated in favor of getParentFragmentManager() to make it clear that you want to access the fragment manager of the parent instead of any child fragments.

Simply use getParentFragmentManager() in Java or parentFragmentManager in Kotlin.


You can simply access like

Context mContext;

public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

mContext = getActivity();

}

and then use

FragmentManager fm = ((FragmentActivity) mContext)
                        .getSupportFragmentManager();

Try this:

private SectionsPagerAdapter mSectionsPagerAdapter = new SectionsPagerAdapter(getActivity().getSupportFragmentManager());

You can use childFragmentManager inside Fragments.


getActivity().getFragmentManager() This worked or me.

Also take a look at here.


You can use getActivity().getSupportFragmentManager() anytime you want to getSupportFragmentManager.

hierarchy is Activity -> fragment. fragment is not capable of directly calling getSupportFragmentManger but Activity can . Thus, you can use getActivity to call the current activity which the fragment is in and get getSupportFragmentManager()


All you need to do is using

getFragmentManager()

method on your fragment. It will give you the support fragment manager, when you used it while adding this fragment.

Fragment Documentation


getSupportFragmentManager() used when you are in activity and want to get a fragment but in the fragment you can access

getSupportFragmentManager()

by use another method called getFragmentMangaer() works the same like getSupportFragmentManager() and you can use it like you used to:

fragmentTransaction =getFragmentManager().beginTransaction();

The following code does the trick for me

 SupportMapFragment mapFragment = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map));
    mapFragment.getMapAsync(this);

Kotlin users try this answer

(activity as AppCompatActivity).supportFragmentManager

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to android-fragments

FragmentActivity to Fragment How to start Fragment from an Activity How to use data-binding with Fragment In android how to set navigation drawer header image and name programmatically in class file? Android Fragment onAttach() deprecated How to convert any Object to String? Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which? Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments java.lang.IllegalStateException: Fragment not attached to Activity java.lang.NullPointerException: Attempt to invoke virtual method 'int android.view.View.getImportantForAccessibility()' on a null object reference

Examples related to android-support-library

No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. when updating to Support Library 26.0.0 Failed to resolve: com.android.support:cardview-v7:26.0.0 android Setting up Gradle for api 26 (Android) How to make ConstraintLayout work with percentage values? Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio Change EditText hint color when using TextInputLayout Cannot resolve symbol AppCompatActivity - Support v7 libraries aren't recognized? Error inflating class android.support.design.widget.NavigationView FloatingActionButton example with Support Library How to use and style new AlertDialog from appCompat 22.1 and above

Examples related to android-fragmentactivity

Manage toolbar's navigation and back button from fragment in android Android check null or empty string in Android Hide/Show Action Bar Option Menu Item for different fragments Android ViewPager with bottom dots How can I access getSupportFragmentManager() in a fragment? Default Activity not found in Android Studio startActivityForResult() from a Fragment and finishing child Activity, doesn't call onActivityResult() in Fragment Setting Custom ActionBar Title from Fragment Start an activity from a fragment Android - Activity vs FragmentActivity?

Examples related to fragmentmanager

How can I access getSupportFragmentManager() in a fragment?