这是我的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();