Leopik
Leopik

Reputation: 333

Endless ViewPager (not looped)

I want to create ViewPager and each page will contain unique data (for example simple textview with integers from 1 to 1000000) and I want to make user see first page with number 500000 (so he will be in the middle of viewpager). I tryed using FragmentStatePagerAdapter with overrided method

getCount() { return 500000 } and

getItem(int position) { return MyCustomFragment.newInstance(position) }

and then set my viewpager.setCurrentItem(50000, false) but when I start app it crashes with OutOfMemory exception. But if I remove viewpager.setCurrentItem(50000, false) then everything works nice, but user starts with first page, not with 50000. As I understand OutOfMemory is thrown because when I set current item to 50000 fragmentadapter tryes to load every fragment from 1 to 50000 and keeps them in memory. So how can I avoid such problem? Probably I should find another solution, but I don't know how to solve my problem with some other way

UPD: here is code that doesnt work:

protected void onCreate(Bundle savedInstanceState) { 

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one_day_schedule);
        mViewPager = (ViewPager) findViewById(R.id.day_page);
        mViewPager.setAdapter(new SchedulePagerAdapter(getSupportFragmentManager()));

        // Puts user in the middle of viewpager
        mViewPager.setCurrentItem(Integer.MAX_VALUE/2, false);
    }

    public static class SchedulePagerAdapter extends FragmentStatePagerAdapter {

        public SchedulePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        // This doesnt work even with empty fragment
        @Override
        public Fragment getItem(int position) {
            return new Fragment()
        }

        @Override
        public int getCount() {
            // Makes viewpager almost infinite
            return Integer.MAX_VALUE;
        }
    }

Upvotes: 1

Views: 237

Answers (1)

Atef Hares
Atef Hares

Reputation: 4891

Try to override these methods:

 @Override
    public int getCount() {
        return Integer.MAX_VALUE;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        String title = mTitleList.get(position % mActualTitleListSize);
        return title;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        int virtualPosition = position % mActualTitleListSize;
        return super.instantiateItem(container, virtualPosition);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        int virtualPosition = position % mActualTitleListSize;
        super.destroyItem(container, virtualPosition, object);
    }

Upvotes: 1

Related Questions