Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
504 views
in Technique[技术] by (71.8m points)

android - My fragments in viewpager tab dont refresh

i got viewpager with 4 tabs .. in each tab there is a fragment. my first tab is a fragment with a form (for example Users) after i click save, the data is inserted in the database. my second tab is another fragment with form but it uses data from the first tab (i am getting it from the database) to populate a spinner. now after i successfully inserted data from my first tab, in my second tab the spinner is empty. since my db query is implemented in onCreateView() in the second fragment, its called only once when the application is started, so changing between tab 1 i tab2 doesn't starts onCreateView() or even onResume(). The interesting thing for me is that if i go to tab4 and then return to tab2, my data is in my spinner properly, so somehow swiping two tabs away from my current tab refreshing my fragment. my question is how can i achieve proper refresh to my fragment when onCreateView() is called only once ?

Edit i tried to put that method psykhi suggested like that:

    this.mViewPager.setOffscreenPageLimit(0);
    this.mViewPager.setAdapter(this.mPagerAdapter);
    this.mViewPager.setOnPageChangeListener(this);

but it's not working for me. Am i missing something ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The best way that I have discovered to simulate a "setOffscreenPageLimit(0)" behavior is by using an OnPageChangeListener in conjunction with overriding the getItemPosition method in your adapter. Something like this:

In your custom pager adapter:

@Override
public int getItemPosition(Object object) {
     return POSITION_NONE;
}

Then in your Activity containing the ViewPager:

final MyPagerAdapter adapter = new MyPagerAdapter();
pager.setAdapter(adapter);
pager.setOnPageChangeListener(new OnPageChangeListener() {
     @Override
     public void onPageSelected(int position) {
          ... anything you may need to do to handle pager state ...
          adapter.notifyDataSetChanged(); //this line will force all pages to be loaded fresh when changing between fragments
     }
}

This should have the same effect as setting the OffscreenPageLimit to 0. However, this functionality is sort of against what the ViewPager is designed to provide. If you are trying to implement a ViewPager in this way, it may be worth reevaluating your layout to be sure that a ViewPager is really what you want to use.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...