【发布时间】:2016-12-30 23:14:14
【问题描述】:
我想在 Fragment 中有一个 MapView。 好像很简单……还是看不懂!
启动应用程序时出现此错误:
java.lang.NullPointerException:尝试调用接口方法 空对象引用上的“void maps.ad.y.v()”
我有一个带有 ViewPager 的活动:MainActivity
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
//...onCreate(), etc
public class SectionsPagerAdapter extends FragmentPagerAdapter {
//...
@Override
public Fragment getItem(int position) {
if (position == 0) {
return ClassicFragment.newInstance(position + 1);
// no problem with this one
} else if (position == 1) {
return MyMapFragment.newInstance(position + 1);
// here is my problem
}
}
}
}
还有 2 个片段。 (一个简单,一个带地图) 我无法正确制作的片段:MyMapFragment
public class MyMapFragment extends SupportMapFragment implements OnMapReadyCallback {
View rootView;
private MapView mapView;
private GoogleMap googleMap;
public MyMapFragment() {
}
public static MyMapFragment newInstance(int sectionNumber) {
MyMapFragment fragment = new MyMapFragment();
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_map, container, false);
return rootView;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
mapView = (MapView) rootView.findViewById(R.id.map);
mapView.onCreate(savedInstanceState);
mapView.onResume();
mapView.getMapAsync(this);//when you already implement OnMapReadyCallback in your fragment
}
@Override
public void onMapReady(GoogleMap map) {
googleMap = map;
}
}
最后,这是 MyMapFragment 的 xml (fragment_map.xml)。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.gms.maps.MapView
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
知道我做错了什么吗?
【问题讨论】:
-
@GVillani82 我确实尝试过这个解决方案,但得到了同样的错误:(
-
我建议使用 MapView 而不是双重嵌套片段。这也可能无意中解决了您的问题。
-
@Orbit 我没有解决问题,但代码看起来更好。谢谢
标签: android google-maps-android-api-2 supportmapfragment