Search code examples
androidandroid-fragmentsandroid-viewpagerfragmentstatepageradapter

Android ViewPager and FragmentStatePagerAdapter save visual elements values


In my FragmentActvitiy I am using a ViewPager, which I fill by using FragmentStatePagerAdapter.

When I try to access the fragment views, with intention to get / update visual elements I get a nullpointer exception. I can access all the fragments and their arguments, but their views return null.

MyPageAdapter adapter = (MyPageAdapter) pager.getAdapter();
Fragment fragment;

for (int i=0; i<15; i++) {
    fragment = adapter.getItem(i);
    View v = fragment.getView();
    System.out.println("--- FRAGMENT = " + fragment + "   VIEW = " + v);
}

I am aware that FragmentStatePagerAdapter deletes views to manage memory resources, and that I shouldn't access the views inside my FragmentActivity.

My question is what is the appropriate way of storing / manipulating visual elements of the fragments?

Should I implement OnPageChangeListener in my ViewPager class and somehow store the fragments values to SharedPreferences and than recreate them - Where?


Solution

  • Your fragments should really manage their own views. What you could do is add methods to your fragments that will alert those fragments that they need to update their views. Call those methods from the FragmentStatePagerAdapter or your hosting Activity. Store the desired changes in the Fragment, and then in onCreateview(...) update the views with the new data or whatever you want to change in it.