ViewPager with Nested Fragments?

前端 未结 2 557
萌比男神i
萌比男神i 2021-01-31 12:43

My problem

According to the Google\'s docs:

You can now embed fragments inside fragments. This is useful for a variety of situations in which

相关标签:
2条回答
  • 2021-01-31 13:13

    There is no reason to do any of the outlined hacks. If you're using ViewPager and PagerAdapter (not sure if they existed at the time of the question), you can use a FragmentPagerAdapter to manage the swipeable tab fragments for you.

    class MyFragmentPagerAdapter(
      private val context: Context,
      fragmentManager: FragmentManager
    ) : FragmentPagerAdapter(fragmentManager) {
      override fun getCount() = 2
    
      override fun getItem(position: Int) = when(position) {
        0 -> FirstFragment()
        1 -> SecondFragment()
        else -> throw IllegalStateException("Unexpected position $position")
      }
    
      override fun getPageTitle(position: Int): CharSequence = when(position) {
        0 -> context.getString(R.string.first)
        1 -> context.getString(R.string.second)
        else -> throw IllegalStateException("Unexpected position $position")
      }
    }
    

    And

    class ParentFragment: Fragment() {
      override fun onCreateView(...) = ...
    
      override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewPager.adapter = MyFragmentPagerAdapter(requireContext(), childFragmentManager)
        tabLayout.setupWithViewPager(viewPager)
      }
    }
    
    0 讨论(0)
  • 2021-01-31 13:18

    Try this on your fragment.

    public class Fragment2 extends SherlockFragment {
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.viewpager_main, container, false);
            // Locate the ViewPager in viewpager_main.xml
            ViewPager mViewPager = (ViewPager) view.findViewById(R.id.viewPager);
            // Set the ViewPagerAdapter into ViewPager
            mViewPager.setAdapter(new ViewPagerAdapter(getChildFragmentManager()));
            return view;
        }
    
        @Override
        public void onDetach() {
            super.onDetach();
            try {
                Field childFragmentManager = Fragment.class
                        .getDeclaredField("mChildFragmentManager");
                childFragmentManager.setAccessible(true);
                childFragmentManager.set(this, null);
            } catch (NoSuchFieldException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }
    

    Source: https://www.swipetips.com/actionbarsherlock-side-menu-navigation-nested-viewpager-fragment-tabs-tutorial/

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