rahul
rahul

Reputation: 2661

how to prevent viewpager to initialize next view by default in android?

I have implemented viewpager to show some introduction screens in android App. There are 4 different screens having different animations on it. My problem is that when user is on 0 fragment of viewpager the fragment 1 initialize by default and animation ends in background and when user goes to fragment 1 then there is no animation(as animation has ended when fragment 1 initialized simultaneous with fragment 1) . What I want to do is that when user is on fragment 0 then only fragment 0 should initialize not the next fragment which is fragment 1. and when user goes to fragment 1 then fragment 0 should destroy so that on sliding back to fragment 0 it should initialize again to show animation. How can I do this.

Upvotes: 6

Views: 3085

Answers (2)

Karioki
Karioki

Reputation: 664

You can use fragment call back onResume like in activity to start the animation. link: http://developer.android.com/reference/android/app/Fragment.html#onResume%28%29

Upvotes: 1

snachmsm
snachmsm

Reputation: 19223

you might change ViewPAger pages memory limit by

viewPager.setOffscreenPageLimit(0);

deafult is 1, so one Fragment/View to the left and to the right will stay in memory.

BUT this is poor practise, viewPager is keeping one Fragment/View on each side for better performance and smooth and immediately scroll possibility. I'm suggesting you to create listener for ViewPager which fires animations on scrolled to desired Fragment (not starting animations in onCreateView). check ViewPager.OnPageChangeListener, especially onPageSelected(int position) method

edit: Google admits that setting 0 for limit is weak, in newest versions logcat says:

Requested offscreen page limit 0 too small; defaulting to 1

so you have to use listener for firing animations, it's also better for performance. like you see method you want to use is deprecated by author (Google itself). method from ViewPager class

public void setOffscreenPageLimit(int limit) {
    if (limit < DEFAULT_OFFSCREEN_PAGES) {
        Log.w(TAG, "Requested offscreen page limit " + limit + " too small; defaulting to " +
                DEFAULT_OFFSCREEN_PAGES);
        limit = DEFAULT_OFFSCREEN_PAGES;
    }
    if (limit != mOffscreenPageLimit) {
        mOffscreenPageLimit = limit;
        populate();
    }
}

you might also create own ViewPager or change DEFAULT_OFFSCREEN_PAGES or mOffscreenPageLimit and fire populate(); method, all using Reflections, smth like this

Field f = ViewPager.class.getDeclaredField("DEFAULT_OFFSCREEN_PAGES");
f.setAccessible(true);
f.setInt(viewPager, 0);

then setOffscreenPageLimit(0); should work

Upvotes: 4

Related Questions