How can I access getSupportFragmentManager() in a

2019-01-04 19:52发布

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);

13条回答
ら.Afraid
2楼-- · 2019-01-04 20:05

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.

查看更多
倾城 Initia
3楼-- · 2019-01-04 20:07

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().

查看更多
虎瘦雄心在
4楼-- · 2019-01-04 20:10

The following code does the trick for me

 SupportMapFragment mapFragment = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map));
    mapFragment.getMapAsync(this);
查看更多
贪生不怕死
5楼-- · 2019-01-04 20:13

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();
查看更多
Juvenile、少年°
6楼-- · 2019-01-04 20:17

Kotlin users try this answer

(activity as AppCompatActivity).supportFragmentManager
查看更多
做个烂人
7楼-- · 2019-01-04 20:18

do this in your fragment

getActivity().getSupportFragmentManager()
查看更多
登录 后发表回答