我有一个FragmentActivity,我想在其中使用一个地图片段。我有一个问题,让支持片段管理器访问它。

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

当前回答

在你的片段中这样做吗

getActivity().getSupportFragmentManager()

其他回答

我的父活动扩展了AppCompatActivity,所以我不得不将我的上下文转换为AppCompatActivity而不仅仅是Activity。

eg.

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

getFragmentManager()已被弃用,取而代之的是getParentFragmentManager(),以清楚地表明您希望访问父片段的片段管理器,而不是任何子片段。

简单地使用Java中的getParentFragmentManager()或Kotlin中的parentFragmentManager。

在片段中获取fragmentManager的最佳方法是调用新方法

getParentFragmentManager()

或者在kotlin文件中使用属性访问语法

parentFragmentManager

这指定了将要加载的fragmentManager(在子片段和父片段之间选择)

Kotlin用户尝试这个答案

(activity as AppCompatActivity).supportFragmentManager
((AppCompatActivity) getActivity()).getSupportFragmentManager()