不會調用onMapReady函數。它需要被觸發才能正確初始化我的GoogleMap。使用片段時不會觸發OnMapReadyCallback
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}
}
我應該繼承MapFragment,而不是片段?因爲我得到另一個錯誤,當我做的事:它MainActivity返回一個NullPointerException
import android.os.Bundle;
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.OnMapReadyCallback;
public class MapsFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap mMap;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_maps, container, false);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
}
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:name=".fragment.MapsFragment"
android:id="@+id/maps_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent">
</fragment>
</LinearLayout>
activity_maps.xml
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".fragment.MapsFragment" />
非常感謝夥計們!
更新1: 將此添加到MapsActivity,但現在MainActivity返回android.view.InflateException:二進制XML文件6號線:錯誤充氣類片段
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SupportMapFragment supportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(this);
}
SupportMapFragment 「無法訪問聲明」 –
我編輯我的答案請 – mdDroid