【问题标题】:How to access map fragment from main view如何从主视图访问地图片段
【发布时间】:2014-05-15 15:28:08
【问题描述】:

我有一个扩展片段和扩展 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();

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

【问题讨论】:

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


    【解决方案1】:

    您正在混合使用 Fragment 和 SupportFragment。到处使用 SupportFragment:

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

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

    【讨论】:

    • 它不喜欢这样:mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
    • 太棒了,实际上我是如何编写代码的,我只需要做你的第一个要点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多