How to pass a string between fragments in a viewpager

后端 未结 2 1603
醉酒成梦
醉酒成梦 2021-01-22 06:11

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 MyFragmentPag         


        
相关标签:
2条回答
  • 2021-01-22 06:28

    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:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.fragment_main, container, false);
    
        String result = container.getTag().toString();
        // do something with the result
    
        return 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.

    0 讨论(0)
  • 2021-01-22 06:37

    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 !

    0 讨论(0)
提交回复
热议问题