【发布时间】:2016-06-13 16:56:57
【问题描述】:
永远不会调用 onMapReady 函数。需要触发它才能正确初始化我的 GoogleMap。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}
}
我应该继承 MapFragment 而不是 Fragment?因为当我这样做时出现另一个错误:它在 MainActivity
中返回 NullPointerExceptionimport 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: Binary XML file line #6: Error inflating class fragment
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SupportMapFragment supportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(this);
}
【问题讨论】: