Reputation: 24443
Please tell me how to reset the content of ViewPager on android. I tried to call adapter.notifyDataSetChanged() but the adapter doesn't call getItem(position) when I scroll the view. It always returns old child views.
Update: This is my Fragment View. When I reset viewPager data, It used loaded Fragment views. It's just start at the onCreateView instead of Constructor.
public class ResultView extends Fragment {
//Declare properties
//Constructor
public ResultView(Province province, Calendar calendar) {
Log.d("xskt", "ResultView constructor");
this.province = province;
this.calendar = (Calendar) calendar.clone();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d("xskt", "ResultView onCreateView");
View view = inflater.inflate(R.layout.resultview, null);
//do some thing
return view;
}
Thanks.
Upvotes: 6
Views: 15446
Reputation: 1
It works if you do the following:
In your Activity or wherever you want to refresh the data:
viewPager.invalidate();
fragmentStatePageAdapter.notifyDataSetChanged();
In you FragmentStatePageAdapter:
@Override
public int getItemPosition(@NotNull Object object) {
return POSITION_NONE;
}
Upvotes: 0
Reputation: 1415
I think the best solution to reload fragments in another fragment is :
@Override
public void onPause() {
super.onResume();
List<Fragment> fragments = getFragmentManager().getFragments();
if (fragments != null) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
for (Fragment fragment : fragments) {
if (fragment instanceof Fragment) {
fragmentTransaction.remove(fragment);
}
}
fragmentTransaction.commitNowAllowingStateLoss();
}
}
Check for your use case whether commitNowAllowingStateLoss
or commitAllowingStateLoss
is necessary.
Upvotes: 2
Reputation: 24443
I have changed to use FragmentStatePagerAdapter
instead of FragmentPagerAdapter
, the problem is resolved. Hope this helps.
Upvotes: 39
Reputation: 19446
One method is to use the observer pattern. The data you are presenting is likely in an sqlite DB (or in stored in memory). You can set a listener in your fragment that will make the necessary updates to your fragment when the data is changed.
Upvotes: 0