Skip to content Skip to sidebar Skip to footer

Updating Fragments From Activity In A ViewPager

I'm new to Android developing and I would really appreciate some help here. I'm using a fragment that contains a TextView and I'm using 5 instances of the same MyFragment class. I

Solution 1:

The easiest way to update those fragments is to use your code and set the number of fragments that the ViewPager holds in memory to the number of total fragments - 1(so all fragments are valid no matter at what page you are). In your case:

pager.setOffscreenPageLimit(4); // you have 5 elements

You can still use the method from my comment with the method onPageScrollStateChanged(so the update will start the moment the user starts swiping) to see when the user is starting to swipe the pager and update the fragments to the left and right of the currently visible fragment, but this will be a bit difficult to get right so I recommend to go with the first option.

Some points regarding your code containing fragments:

If you nest the fragment class make it static so you don't tie it to the activity object. Don't create a constructor for a Fragment besides the default one. If the framework needs to recreate the fragment it will call the default constructor and if it is not available it will throw an exception. For example, try to change the orientation of the phone/emulator and see what happens(this is one of the cases when Android will recreate the fragments). Last, use a custom name for the ViewPager's adapter, you use PagerAdapter which is the name of the super class of FragmentViewPager and it's very confusing for someone reading your code.

If you need to pass data to the Fragment you could use a creation method like the one below:

public static MyFragment newInstance(String text) {
        MyFragment f = new MyFragment();
        Bundle b = new Bundle();
        b.putString("content", text);
        f.setArguments(b);
        return f;
    }

The text will be available in MyFragment by using getArguments().getString("content");


Post a Comment for "Updating Fragments From Activity In A ViewPager"