Skip to content Skip to sidebar Skip to footer

How To Pass A String Between Fragments In A Viewpager

I'm trying to pass a string between two fragments in a viewpager but I didn't found the right way to do it. Here is my code so far : public class MyFragmentPagerAdapter extends Fra

Solution 1:

You're obviously using ViewPager and you can take advantage of it. You can add a tag to a ViewPager like this:

Activity:

pager.setTag("some text");  // pager is a ViewPager object

Then you can get this data via ViewGroup in a fragment like this:

Fragment:

@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    Viewview=  inflater.inflate(R.layout.fragment_main, container, false);

    Stringresult= container.getTag().toString();
    // do something with the resultreturn view;

You can also setTag() to the container in the fragment.

This is the cleanest solution I found for sending data among fragments and their mother activity. Another solution (not mentioned here so far) is sending data through SharedPreferences, but I would suggest using tags if possible.

Solution 2:

So i found the solution, the implementation is correct, the only thing that I should do the treatement I want in the method on the second fragment and that's it !

Post a Comment for "How To Pass A String Between Fragments In A Viewpager"