简体   繁体   中英

View pager different results

I am using view pager with 3 tabs in MainActivity of my app to show grid images. I have one MovieFragment for all 3 tabs and I am using FragmentsPagerAdapter to create new instance of MovieFragment everytime tab is changed.

//FragmentsPagerAdapter method
@Override
public Fragment getItem(int position) {
    switch (position){
        case 0: return MoviesFragment.newInstance(buildUrl(Utility.POPULAR_URL));
        case 1: return MoviesFragment.newInstance(buildUrl(Utility.RATED_URL));
        case 2: return MoviesFragment.newInstance("favorite");
        default: return null;
    }
}

//Fragment method
public static MoviesFragment newInstance(String uri){
    MoviesFragment fragment = new MoviesFragment();
    Bundle bundle = new Bundle();
    bundle.putString("fragment", uri);
    fragment.setArguments(bundle);
    return fragment;
}

Now I was getting different results in my app so I debugged this method and I found it calls methods before tab is selected ie when I open app it creates instances for case 0 and case 1 and when I go to second tab it creates instance for case 2 . Now in my second tab when I make changes to database and try to get them in third tab changes are not reflected as it already created instance of third tab when second tab was selected. How do I solve this problem?

@Sahil This is because in android ViewPager keeps track of previous and next pages only. So when you initialize the viewPager it automatically create first 2 page and call MoviesFragment for 1st two tab. And once you start scrolling through, it starts keeping the track of only previous and next page.

Read this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM