android mapfragment以编程方式

时间:2015-04-28 09:23:04

标签: android google-maps fragment mapfragment

我希望将Android地图v2插入片段,但我的意思是我不能使用.xml文件。当我尝试实例化MapFragment时出现问题。这是代码:

public class LocationFragment extends Fragment{

    private static View view;
    private static GoogleMap mMap;

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

        if (container == null) {

            return null;
        }
        view = (RelativeLayout) inflater.inflate(R.layout.location_fragment, container, false);

        setUpMapIfNeeded(); // For setting up the MapFragment

        MapFragment mf = new MapFragment();

        return view;
    }

    /***** Sets up the map if it is possible to do so *****/
    public static void setUpMapIfNeeded() {

        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {

            FragmentManager manager = MapActivity.fragmentManager;
            MapFragment smf = (MapFragment) manager.findFragmentById(R.id.location_map);
            mMap = smf.getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null)
                setUpMap();
        }
    }

有人能帮助我吗?

2 个答案:

答案 0 :(得分:1)

如果您正在使用片段,我建议使用以下内容:

public class MapFragment extends Fragment {

     private static GoogleMap mMap;
     private static UiSettings mUiSettings;

     @Override
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
          final View rootView = inflater.inflate(R.layout.conduccion_map, container, false);

          if (mMap == null)
             mMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapfragment)).getMap();

          mMap.setMyLocationEnabled(true);
          mUiSettings = mMap.getUiSettings();
          mUiSettings.setZoomControlsEnabled(false);
          mUiSettings.setCompassEnabled(true);
          mUiSettings.setMyLocationButtonEnabled(true);


         return rootView;
     }
}

PagerAdapter调用此片段的代码可能是这样的:

class AppSectionsPagerAdapter extends FragmentStatePagerAdapter {

    public AppSectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public int getCount() {
        return NUM_PAGES;
    }

    @Override
    public Fragment getItem(int i) {
        switch (i) {
            case 0:
                // Map Fragment Activity
                return new MapFragment();

            default:
                return null;
        }
    }
}

希望这有帮助!

答案 1 :(得分:0)

你应该真的使用getMapAsync()。但是你可以做这样的事情,使用片段事务以编程方式添加地图片段。

MapFragment smf = MapFragment.newInstance(); manager.beginTransaction() .add(FRAGMENT_CONTAINER_ID, smf) .commit();