MapView没有从ViewPager中删除?

时间:2012-05-10 08:22:07

标签: android android-viewpager

在我的应用程序中,我正在尝试在ViewPager中实现地图视图。我在应用程序中有4个不同的页面。和MapView在第4页。我成功加载了地图,但是当我滑回第一页时,必须使用destroyItem()方法销毁第4个视图。如果我滑到第4页,它会从第3页崩溃,显示logcat中的错误:

05-10 13:14:50.152: E/AndroidRuntime(620): java.lang.IllegalStateException: You are only allowed to have a single MapView in a MapActivity

我知道MapActivity中只有一个mapview。但是我无法解决它 - 任何人都可以帮助我吗?

代码如下:

public Object instantiateItem(View collection, int position) {

   LayoutInflater inflater = (LayoutInflater) collection.getContext()
         .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   context = collection.getContext();
   int resId = 0;
   int flag = resId;
   switch (position) {
   case 0:
      resId = R.layout.farleft; // first
      view = inflater.inflate(resId, null);

      break;
   case 1:
      resId = R.layout.left; // second
      view = inflater.inflate(resId, null);

      break;
   case 2:
      resId = R.layout.right; // third
      view = inflater.inflate(resId, null);

      break;
   case 3:
      resId = R.layout.mylocator;
      view = inflater.inflate(resId, null);
      break;

   }
   ((ViewPager) collection).addView(view, 0);

   return view;
}

@Override
public void destroyItem(View arg0, int arg1, Object arg2) {

   ((ViewPager) arg0).removeView((View) arg2);
   Log.d("destroyItem", "" + arg2);
}

2 个答案:

答案 0 :(得分:1)

我找到了解决方案。 在包含Map并且ViewPager使用的片段内,放置:

private View myView;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    if (this.myView == null){
        this.myView = inflater.inflate(R.layout.my_layout, container, false);
    }
    else if (this.myView.getParent() != null) {
        FrameLayout parentView = (FrameLayout) this.myView.getParent();
        parentView.removeView(this.myView);
    }

    return this.myView;

}

它适用于我,告诉我它是否适合你;)

答案 1 :(得分:0)

Android View Pager的一个问题是回收视图必须手动完成。在您的情况下,视图可能尚未被销毁,但是在再次实例化视图时第二次创建。您可以保存每个页面的视图,然后在instantiateItem中返回它,如果它尚未被销毁的话。