我遇到错误
试图调用虚拟方法'void
com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
但是我已经完成了每个站点的所有操作,我不知道错误是什么,请帮助我在OnViewCreated中完成操作,并使用子片段也仍然会出现错误
package com.example.tanis.myapplication;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
/**
* A simple {@link Fragment} subclass.
*/
public class ContactUs extends Fragment implements OnMapReadyCallback {
GoogleMap map;
public ContactUs() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate( R.layout.fragment_contact_us, container, false );
return v ;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated( view, savedInstanceState );
SupportMapFragment mapFragment = (SupportMapFragment)getChildFragmentManager().findFragmentById( R.id.map1 );
mapFragment.getMapAsync( this );
}
@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;
LatLng pp = new LatLng( 28.6403159,77.376114);
MarkerOptions options = new MarkerOptions();
options.position( pp ).title( "WebTechniq" );
map.addMarker( options );
map.moveCamera( CameraUpdateFactory.newLatLng( pp ) );
}
}
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.tanis.myapplication.ContactUs">
<!-- TODO: Update blank fragment layout -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/map1"
tools:context=".MapsActivity"
class="com.google.android.gms.maps.SupportMapFragment" />
</android.support.constraint.ConstraintLayout>
答案 0 :(得分:0)
将您的 RelativeLayout 更改为片段。
要使用SupportMapFragment,您总是需要在xml中有一个可以放置其布局的片段。
有关它的更多信息,请参考android的official document
答案 1 :(得分:0)
片段SupportMapFragment
不起作用...解决此问题使用MapView
。
在MapView
中使用fragment
的情况,请参见此答案...
https://stackoverflow.com/a/19354359/9868485