我有一个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);

当前回答

你可以简单地访问

Context mContext;

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

mContext = getActivity();

}

然后使用

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

其他回答

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

eg.

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

你可以简单地访问

Context mContext;

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

mContext = getActivity();

}

然后使用

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

下面的代码为我完成了这个任务

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

您可以直接拨打

getParentFragmentManager()  

获取片段管理器。注意,getFragmentManager()也可以工作,但已被标记为已弃用。