Mapbox不在片段中工作

时间:2016-04-02 04:31:11

标签: java android android-fragments android-fragmentactivity mapbox

我正在尝试在片段中显示一个mapbox但是我收到以下错误:

public class Map extends android.support.v4.app.Fragment { private MapView mapView; public Map() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View layout = inflater.inflate(R.layout.fragment_map, container, false); MapView mapView = (MapView) layout.findViewById(R.id.mapview); mapView.onCreate(savedInstanceState); mapView.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(MapboxMap mapboxMap) { // Set map style mapboxMap.setStyleUrl(Style.MAPBOX_STREETS); // Set the camera's starting position CameraPosition cameraPosition = new CameraPosition.Builder() .target(new LatLng(41.885, -87.679)) // set the camera's center position .zoom(12) // set the camera's zoom level .tilt(20) // set the camera's tilt .build(); // Move the camera to that position mapboxMap.moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); } }); return layout; } @Override public void onResume() { super.onResume(); mapView.onResume(); } @Override public void onPause() { super.onPause(); mapView.onPause(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mapView.onSaveInstanceState(outState); } @Override public void onLowMemory() { super.onLowMemory(); mapView.onLowMemory(); } @Override public void onDestroy() { super.onDestroy(); mapView.onDestroy(); } }

这是Map片段类:

{{range $index, $element := .Products}}
    {{if $index % 4 == 0}}<div class="row">{{end}}
        <div class="columns small-3 product">
            <img src="/img/{{.ImageUrl}}" alt="{{.ImageUrl}}" />
                <a href="/product">
                    <h3>{{.Title}}</h3>
                </a>
                <p>
                  {{.Description}}
                </p>
                <p>
                    {{.Price}} / liter
                </p>
                </div>
        {{if index % 4 == 0}}</div>{{end}}
{{end}}

我在这里遗漏了什么吗?我关注此链接:https://www.mapbox.com/help/first-steps-android-sdk/

1 个答案:

答案 0 :(得分:4)

您有两个mapview实例。一个是oncreate方法中的局部变量,另一个是全局变量。

并且全局变量没有初始化,所以改变这一行

MapView mapView = (MapView) layout.findViewById(R.id.mapview);

进入这个

mapView = (MapView) layout.findViewById(R.id.mapview);

我认为你理解这个问题。