Getting error in viewpager adapter,java.lang.IllegalStateException: The specified child already has a parent

568 Views Asked by At

I am trying to use viewpager with images but it shows only one picture if I slides it crashes, Saying java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. My adapter code is:

public class NewDemoAdapter extends PagerAdapter {
    public ArrayList<Integer> imagelist;
    public ArrayList<String> lines;
    public Context context;
    private ImageView imageView;
    private BitmapFactory.Options bounds;
    private ViewGroup viewPager;
    private Bitmap cropImg;
    private LayoutInflater mInflater;

    public NewDemoAdapter(Context context, ArrayList<Integer> imagelist, ArrayList<String> line) {

        this.imagelist = imagelist;
        this.lines = line;


    }


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

    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

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

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {

        mInflater = LayoutInflater.from(AppController.getAppContext());
        final View itemView = mInflater.inflate(R.layout.demolayout,container,false);

        ImageView imageView = (ImageView) itemView.findViewById(R.id.myimage);
        TextView textView = (TextView) itemView.findViewById(R.id.line);
        textView.setText(lines.get(position));
        imageView.setImageResource(imagelist.get(position));
        ((ViewPager) container).addView(imageView, 0);

        return itemView;
    }

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

}
1

There are 1 best solutions below

1
On BEST ANSWER

The issue is this line

((ViewPager) container).addView(imageView, 0);

ImageView (R.id.image) has as parent itemView , which means it can't have also the ViewPager as parent. Change

((ViewPager) container).addView(imageView, 0);

to

((ViewPager) container).addView(itemView, 0);

Edit

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