Android 如何从主视图访问地图片段

Android 如何从主视图访问地图片段,android,google-maps,android-fragments,android-mapview,Android,Google Maps,Android Fragments,Android Mapview,我有一个java类,它扩展了片段并扩展了xml布局。下面是我为该java类编写的代码: import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.vi

我有一个java类,它扩展了片段并扩展了xml布局。下面是我为该java类编写的代码:

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;

/**
 * Created by Mike on 3/17/14.
 */
public class BreweryMap extends Fragment {

    public BreweryMap(){}

    String beerId = "";

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

        View rootView = inflater.inflate(R.layout.activity_brewmap, container, false);
        setHasOptionsMenu(true);

        //get user information
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        String userName = prefs.getString("userName", null);
        String userID = prefs.getString("userID", null);


        //call async to get breweries to add to


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


        //add url
        String url = "hmyURL";

        //send mMap over with async task
        new GetVisitedBreweries(getActivity(), mMap).execute(url);


        return rootView;
    }


}
以下是正在膨胀的xml布局:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:name="com.google.android.gms.maps.MapFragment"/>
查看我的代码后,我认为为空是有意义的,因为它正在查找的片段ID位于我的rootView中,存储在此行:

    mMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    View rootView = inflater.inflate(R.layout.activity_brewmap, container, false);
如何从我的rootView成功访问地图片段?

我试过:

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

和其他组合。我觉得我很接近,但不是很接近

您正在混合Fragment和SupportFragment。在任何地方使用SupportFragment:

  • 在布局中:使用
    com.google.android.gms.maps.SupportMapFragment

  • 在onCreate()中:使用
    getSupportFragmentManager()


它不是这样的:mMap=((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap();太棒了,实际上我是如何编写代码的,我只需要做你的第一个要点。