Placing SupportMapFragment on DialogFragment

后端 未结 3 1909
野趣味
野趣味 2021-01-06 17:00

I\'m trying to add SupportMapFragment on DialogFragment, but it return error inflating class fragment. I cannot figure it out why its returned error infla

相关标签:
3条回答
  • 2021-01-06 17:36

    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();
    }
    
    0 讨论(0)
  • 2021-01-06 17:45

    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.

    0 讨论(0)
  • 2021-01-06 17:47

    Try this..

    Change this..

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

    to

    mapDetail = ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map_data))
                    .getMap();
    
    0 讨论(0)
提交回复
热议问题