Get current fragment with ViewPager2

后端 未结 11 1848
野的像风
野的像风 2020-12-24 01:15

I\'m migrating my ViewPager to ViewPager2 since the latter is supposed to solve all the problems of the former. Unfortunately, when using it with a

11条回答
  •  时光说笑
    2020-12-24 01:30

    I also had your problem and used this trick

        Map map = new HashMap<>();
    
    @Override
            public Fragment createFragment(int position) {
                Fragment fragment;
                switch (position) {
                    case 0:
                        fragment = new CircularFragment();
                        map.put(0, fragment);
                        return fragment;
                    case 1:
                        fragment = new LocalFragment();
                        map.put(1, fragment);
                        return fragment;
                    case 2:
                        fragment = new SettingsFragment();
                        map.put(2, fragment);
                        return fragment;
                }
                fragment = new CircularFragment();
                map.put(0, fragment);
                return fragment;
            }
    

    and you can get fragment like this

     LocalFragment f = (LocalFragment) map.get(1);
    

提交回复
热议问题