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

前端 未结 2 493
陌清茗
陌清茗 2020-12-30 06:52

I\'m an android beginner, trying to learn, and this is my first question, so please excuse me if the question is too simple and please tell me if I\'m using the forum incorr

相关标签:
2条回答
  • 2020-12-30 07:10

    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
    
    0 讨论(0)
  • 2020-12-30 07:26

    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

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