How do I pass a variable through a FragmentPagerAdapter to a Fragment?

放肆的年华 提交于 2019-11-30 09:12:43
moskis

I extract this from the original Google Samples.

Fragment:

public class IntegerFragment extends Fragment {
    int imageResourceId;
    int numberSelected;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //change to avoid orientation crash
        imageResourceId = getArguments().getInt("param");
        numberSelected = getArguments().getInt("number");
    }
    
    public static Fragment newInstance(int imageResourceId, int numberSelected) {
        IntegerFragment f = new IntegerFragment();
        f.imageResourceId = imageResourceId;
        f.numberSelected = numberSelected;
        return f;
    }

FragmentPagerAdapter

public class MyIntegerAdapter1 extends FragmentPagerAdapter {
    private Fragment[] fragments;

    public MyIntegerAdapter1(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
        case 0:
        if (content != null && position < content.length) {
        if (fragments[position] == null) {
            fragments[position] = IntegerFragment.newInstance(R.drawable.image1, 1);
        }
        return fragments[position % fragments.length];
    }
    return null;
etc
David Walton

Problem over. I found out (from the link below) how a fragment can call a method in its activity. That method is providing the value. I'm not sure it's the best way but it's simple and it works.

Passing data between a fragment and its container activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!