PagerAdapter中的MapFragment

时间:2016-06-08 12:53:37

标签: android android-viewpager android-maps-v2 android-pageradapter

我正在尝试在PagerAdapter中加载Mapfragment。这是适配器代码,

public class ShopPagerAdapter extends PagerAdapter {

    private List<LoyaltyOutlet> data;
    private Context context;
    FragmentManager fragmentManager;

    public ShopPagerAdapter(List<LoyaltyOutlet> data, Context context,FragmentManager manager) {
        this.data = data;
        this.context = context;
        this.fragmentManager = manager;
    }

    @Override
    public Object instantiateItem(ViewGroup collection, int position) {
        LoyaltyOutlet outlet = data.get(position);
        LayoutInflater inflater = LayoutInflater.from(context);
        ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.fragment_loyalty_shop_item, collection, false);
        TextView address = (TextView)layout.findViewById(R.id.txt_ShopAddress);
        GoogleMap googleMap = ((SupportMapFragment) fragmentManager.findFragmentById(R.id.shopMap)).getMap();
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
        googleMap.animateCamera(cameraUpdate);
        address.setText(outlet.getOutletName());

        collection.addView(layout);
        return layout;

    }

    @Override
    public void destroyItem(ViewGroup collection, int position, Object view) {
        collection.removeView((View) view);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return "";
    }

}

但是当我运行代码时,我得到了一个例外,

  

java.lang.NullPointerException:尝试调用虚方法   “com.google.android.gms.maps.GoogleMap   com上的com.google.android.gms.maps.SupportMapFragment.getMap()'   对象参考

是否可以在此处使用MapFragment,还是应该在片段生命周期方法中移动此代码?

感谢。

1 个答案:

答案 0 :(得分:0)

这是我使用MapView实现它的方法。希望这会有所帮助

片段的Xml

char* h_pattern;
h_pattern = (char*) malloc((size_t) 40* size * sizeof(char));

Java代码

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <com.google.android.gms.maps.MapView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>