我目前正在测试 Android 中的 viewpager。创建了一个自定义适配器,但是当我尝试滑动 viewpager 时出现此错误。谁能帮我解决这个问题?
public class ViewPagerAdapter extends PagerAdapter {
Context context;
int[] flag;
LayoutInflater inflater;
public ViewPagerAdapter(Context context, int[] flag) {
this.context = context;
this.flag = flag;
}
@Override
public int getCount() {
return flag.length;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imgflag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.viewpager_item, container, false);
//ImageView imageView = new ImageView(context);
//imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
//imageView.findViewById(R.id.flag);
imgflag = (ImageView) itemView.findViewById(R.id.flag);
imgflag.setImageResource(flag[position]);
((ViewPager) container).addView(imgflag);
return imgflag;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
日志猫:
05-02 10:35:26.926: E/AndroidRuntime(4939): FATAL EXCEPTION: main
05-02 10:35:26.926: E/AndroidRuntime(4939): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
理查德建议的编辑:
public class ViewPagerAdapter extends PagerAdapter {
Context context;
int[] flag;
LayoutInflater inflater;
ImageView imgflag;
View itemView;
public ViewPagerAdapter(Context context, int[] flag) {
this.context = context;
this.flag = flag;
}
@Override
public int getCount() {
return flag.length;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
itemView = inflater.inflate(R.layout.viewpager_item, container, false);
//ImageView imageView = new ImageView(context);
//imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
//imageView.findViewById(R.id.flag);
imgflag = (ImageView) itemView.findViewById(R.id.flag);
imgflag.setImageResource(flag[position]);
((ViewPager) container).addView(itemView);
//return imgflag;
return itemView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
//((ViewPager) container).removeView((ImageView) object);
((ViewPager) container).removeView(itemView);
//((ViewGroup)imgflag.getParent()).removeView(imgflag);
}
}
日志猫:
05-02 10:55:42.786: E/AndroidRuntime(7763): FATAL EXCEPTION: main
05-02 10:55:42.786: E/AndroidRuntime(7763): java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.ImageView