这是我的my_location.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:animateLayoutChanges="true"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/etName" />
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
这是我的代码:
public class MyLocation extends Fragment {
private GoogleMap googleMap;
Context mContext;
public MyLocation (){ mContext = getActivity(); };
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View root = inflater.inflate(R.layout.my_location, container, false);
googleMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
}
}
不幸的是,它在该行显示NPE
googleMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
我做错了什么?
如果我的清单有部分内容
<permission
android:name="com.imincode.meniti.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-permission android:name="com.imincode.meniti.maps.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
使用接受的答案中的链接解决了我的问题!这是我所做的:
我刚换
googleMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
至
googleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map)).getMap();
最佳答案
您的问题与link1 link2 link3
提出问题之前,请先进行搜索。
关于android - 在 fragment 中添加GoogleMap时的NPE,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31708016/