我如何访问片段中的getSupportFragmentManager()?

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

你可以直接打电话

 getFragmentManager() 

得到片段管理器。

要么

在你的片段中,

创建字段:

 private FragmentActivity myContext; 

覆盖片段的onAttach方法:

 @Override public void onAttach(Activity activity) { myContext=(FragmentActivity) activity; super.onAttach(activity); } 

当您需要获得支持片段管理器调用时:

 FragmentManager fragManager = myContext.getSupportFragmentManager(); //If using fragments from support v4 

要么

 FragmentManager fragManager = myContext.getFragmentManager(); 

你完成了。

所有你需要做的就是使用

 getFragmentManager() 

方法在你的片段。 它会给你支持片段管理器,当你在添加这个片段的时候使用它。

片段文档

简单地把它像这样 –

 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. 

要么

 getActivity().getSupportFragmentManager(); 

在你的Fragment的onActivityCreated()方法和onActivityCreated()之后被调用的任何方法中。

您可以随时使用getActivity().getSupportFragmentManager()来获取支持片段管理器。

层次结构是活动 – >片段。 片段不能直接调用getSupportFragmentManger,但Activity可以。 因此,可以使用getActivity来调用片段所在的当前活动并获取getSupportFragmentManager()

如果你有这个问题,并在API级别21+做到这一点:

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

这将在片段内部使用时获得映射。

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

例如。

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

尝试这个:

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

你可以简单地访问像

 Context mContext; public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { mContext = getActivity(); } 

然后使用

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

在你的片段中做这个

 getActivity().getSupportFragmentManager() 

Kotlin用户试试这个答案

 (activity as AppCompatActivity).supportFragmentManager 

getSupportFragmentManager()当你在活动中,并且想要得到一个片段,但在你可以访问的片段中

 getSupportFragmentManager() 

通过使用另一个称为getFragmentMangaer()方法,它和getSupportFragmentManager() ,你可以像以前一样使用它:

 fragmentTransaction =getFragmentManager().beginTransaction();