LvN
LvN

Reputation: 711

Fragment initializes before being visible to the user in viewpager

I am reusing the same fragment to display an image with an animation. The problem which I facing is the fragment view is loaded with the animation before it is visible to the user while swiping. Below is my PagerAdapter

public class PollsAdapter extends FragmentStatePagerAdapter {
/** Constructor of the class */
int clickPosition = 0;
ArrayList<Polls> pollsList = new ArrayList<Polls>();
public PollsAdapter(FragmentManager fm,ArrayList<Polls> pollsList) {
    super(fm);      
    this.pollsList=pollsList;
}

/** This method will be invoked when a page is requested to create */
@Override
public Fragment getItem(int arg0) {     
    PollsFragment myFragment = new PollsFragment();
    Bundle data = new Bundle();     
    data.putSerializable("poll", pollsList.get(arg0));  
    data.putInt("position", arg0);  
    myFragment.setArguments(data);
    return myFragment;
    
}

/** Returns the number of pages */
@Override
public int getCount() {
    return pollsList.size();
}


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

}

This is how I set my viewPager

  pollsAdapter = new PollsAdapter(fm, pollsList);
    viewPager = (ViewPager) _rootView.findViewById(R.id.pager);
    viewPager.setAdapter(pollsAdapter);

I tried by using `viewPager.setOffscreenPageLimit(1); but this didn't work. I'm sure I miss something. Please help me to solve this problem.

Upvotes: 3

Views: 2264

Answers (1)

dhke
dhke

Reputation: 15388

This is --unfortunately-- not possible. To display the flip animation, ViewPager has to pre-load at least the fragments to the left/right of the currently displayed fragment.

Because of this, the minimum possible value for ViewPager.setOffscreenPageLimit() is 1 as at least the direct neighbours need to be available.

In your case, the problem is rather that your fragment seems to be starting an animation as soon at is created.

In that case, you will need to change the starting logic for your animation. Your fragment can get notified by the ViewPager as soon as it is scrolled to (see ViewPager.OnPageChangeListener) for the mechanism). Note that the OnPageListener is not called when your activity is resumed so you also need to handle this case..

How to determine when Fragment becomes visible in ViewPager has more information on that topic.

Upvotes: 2

Related Questions