Android – Inflate new layout xml for each view – instantiateItem in PagerAdapter

androidandroid-viewpagerlayout-inflater

So basically i want to populate the pages inside ViewPager with separate XML layouts for each view position. I'm currently doing this by

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

        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);

        if(position == 0){
        view = inflater.inflate(R.layout.main, null);
        ((ViewPager) container).addView(view, 0);
        }
        if(position == 1){
            view = inflater.inflate(R.layout.main_second, null);
            ((ViewPager) container).addView(view, 0);
        }
        if(position == 2){
            view = inflater.inflate(R.layout.main_third, null);
            ((ViewPager) container).addView(view, 0);
        }

        return view;
}

The views are displayed correctly at first, but when i swipe the ViewPager, the Layout is hidden/destroyed. Why is this? Am i doing it the wrong way? please help and correct me.

Thanks.
Love. Wesley

Best Answer

Check out this link for a good tutorial on how to put it all together. Basically the idea is that you have to add the newly inflated view to the ViewPager collection:

View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
Related Topic