ViewPager中添加百度地图MapView,Page切换时地图显示黑屏问题

在ViewPager的选项卡中增加的Page多余3个,如果在添加MapView的Page和间隔一个Page的那个Page直接切换,会导致地图的Page中的MapView显示黑色,代码如下:

 

LayoutInflater inflater = getLayoutInflater();
//第一个普通的Page
view1 = inflater.inflate(R.layout.raininfo_page_1, null);
view2 = inflater.inflate(R.layout.raininfo_page_2, null);
//带有MapView的Page
view3 = inflater.inflate(R.layout.raininfo_page_3, null);
views.add(view1);
views.add(view2);
views.add(view3);
viewPager.setAdapter(new MyViewPagerAdapter(views));
viewPager.setCurrentItem(0);
viewPager.setOnPageChangeListener(new MyOnPageChangeListener());

 MyViewPagerAdapter的代码:

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    container.removeView(mListViews.get(position));
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
    container.addView(mListViews.get(position), 0);
    return mListViews.get(position);
}

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

 

代码运行后,初始显示第一个Page,如果在第一个Page和第三个Page直接切换,就回发现,MapView会一直显示黑色。解决的办法,就是每次Adapter调用instantiateItem时重新生成加入MapView所在的Page

代码如下(先加入Page1和Page2):

view1 = inflater.inflate(R.layout.raininfo_page_1, null);
view2 = inflater.inflate(R.layout.raininfo_page_2, null);
views.add(view1);
views.add(view2);

  MyViewPagerAdapter的代码(在Adapter的instantiateItem调用时加入Page3):

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

@Override
public Object instantiateItem(ViewGroup container, int position) {
    if(position==2){
        LayoutInflater inflater = getLayoutInflater();
        view3 = inflater.inflate(R.layout.raininfo_page_3, null);
        stationSpreadPage=new RainInfoStationSpreadPage(RainInfoActivity.this,view3);
        container.addView(view3, 0);
        return view3;
    }else{
        container.addView(mListViews.get(position), 0);
        return mListViews.get(position);
    }
}
@Override
public int getCount() {
    return mListViews.size()+1;
}

 程序运行后,切换正常

 

你可能感兴趣的:(移动开发)