How to pass a string between fragments in a viewpager

后端 未结 2 1602
醉酒成梦
醉酒成梦 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.

提交回复
热议问题