我试图在 fragment 中获取 Google map ,但出现 NullPointerException。我已经阅读了类似问题的其他答案,但它们对我没有帮助。
主页 fragment :
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
SupportMapFragment mapFragment = (SupportMapFragment) getFragmentManager()
.findFragmentById(R.id.ftMap);
mapFragment.getMapAsync(this);
return view;
}
fragment_home.xml:
<fragment
android:id="@+id/ftMap"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_centerInParent="true"
android:layout_margin="8dp" />
最佳答案
由于您使用的是嵌套在外部 Fragment 内部的 SupportMapFragment,因此需要使用 getChildFragmentManager()
而不是 getFragmentManager()
:
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.ftMap);
关于android - fragment 内带有 SupportMapFragment 的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41475417/