How to use google map V2 inside fragment?

后端 未结 9 843
攒了一身酷
攒了一身酷 2020-12-02 13:43

I have a fragment which is a part of Viewpager, and I want to use Google Map V2 inside that fragment. This is what I have tried so far,

In my fragment,



        
9条回答
  •  北海茫月
    2020-12-02 13:59

    If I replace the fragment, where the map fragment is in (in this code example MyFragment) with a different fragment and then come back, I get an IllegalStateException

    public class Home_Map extends Fragment {
    
    GoogleMap googleMap;
    FragmentManager myFragmentManager;
    SupportMapFragment mySupportMapFragment;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
         View rootView = inflater.inflate(R.layout.fragment_home__map, container, false);
    
         //googleMap.setMyLocationEnabled(true);
    
            try {
                // Loading map
                initilizeMap();
                googleMap.setMyLocationEnabled(true);
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        return rootView;
    }
     private void initilizeMap() {
    
            try
            {
            if (googleMap == null) {
                myFragmentManager = getFragmentManager();
                mySupportMapFragment = (SupportMapFragment)myFragmentManager.findFragmentById(R.id.map2);
                googleMap = mySupportMapFragment.getMap();
    
                if (googleMap == null) {
                    Toast.makeText(getActivity().getApplicationContext(),
                            "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                            .show();
                }
            }
            } catch (Exception e) { Toast.makeText(getActivity().getApplicationContext(), ""+e, 1).show();
                // TODO: handle exception
            }
        }
    
       @Override
        public void onResume() {
            super.onResume();
    
            initilizeMap();
    
        }
    
       @Override
        public void onDetach() {
            // TODO Auto-generated method stub
            super.onDetach();
              try {
                    Field childFragmentManager = Fragment.class
                            .getDeclaredField("mChildFragmentManager");
                    childFragmentManager.setAccessible(true);
                    childFragmentManager.set(this, null);
    
                } catch (NoSuchFieldException e) {
                    throw new RuntimeException(e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
        }
    
        }
    

提交回复
热议问题