Placing SupportMapFragment on DialogFragment

落花浮王杯 提交于 2019-12-02 01:17:19

Try this..

Change this..

mapDetail = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map_data))
                .getMap();

to

mapDetail = ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map_data))
                .getMap();

I was facing problem while adding GoogleMapFragment inside DialogFragment and I have solved it as

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    if (Build.VERSION.SDK_INT < 21) {
        supportMapFragment = (SupportMapFragment) getActivity()
                .getSupportFragmentManager().findFragmentById(R.id.mapDialog);
    } else {
        supportMapFragment = (SupportMapFragment) getActivity().getSupportFragmentManager()
                .findFragmentById(R.id.mapDialog);
    }
    supportMapFragment.getMapAsync(this);
}

Override onDestroy() as

 @Override
public void onDestroy() {
    super.onDestroy();
    if (null != supportMapFragment)
        getActivity().getSupportFragmentManager().beginTransaction()
                .remove(supportMapFragment)
                .commit();
}
Brian Webb

In case someone else comes along with a similar issue...

To answer your original question, the InflateException (Error inflating class fragment) has occurred because nested fragments - i.e., your SupportMapFragment inside a DialogFragment - may not be inflated from static XML layouts.

See this note from the developer docs:

Note: You cannot inflate a layout into a fragment when that layout includes a <fragment>.
Nested fragments are only supported when added to a fragment programmatically.


So your layout.xml should contain a <FrameLayout.../> for your SupportMapFragment instead of the explicit <fragment.../>, then you'll just add the map fragment via code versus layout inflation.

And since nested fragments must be managed via a FragmentManager from getChildFragmentManager(), you'll want to change the existing getFragmentManager() call when setting up your FragmentTransaction for adding the map fragment programmatically (don't forget to commit!).

For a great example, take another look at the R.layout.mapdialog XML example and associated handling shown in the second SO link you originally included in your question.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!