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

时间:2014-05-15 15:28:08

标签: android google-maps android-fragments android-mapview

我有一个扩展片段并扩展xml布局的java类。下面是我的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"/>

我的空指针错误来自这一行:

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

在查看我的代码之后,对我来说这是有意义的它是NULL,因为它正在寻找的片段ID在我的rootView 中,它存储在这一行:

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

如何从rootView成功访问地图片段?

我试过了:

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

和其他组合。我觉得我很近但不完全。

1 个答案:

答案 0 :(得分:1)

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

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

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