不能在片段中使用addOnTabSelectedListener

时间:2018-02-27 13:46:21

标签: java android

我正在尝试调用一个包含viewpager的片段,以便我可以滑过它。但是当我试图运行代码时,当我到达addOnTabSelectedListener()'时,我遇到了错误。不知道该解决这个问题。有人可以指导我这个。非常感谢你!

错误:

  

尝试调用虚方法' void android.support.design.widget.TabLayout.addOnTabSelectedListener(android.support.design.widget.TabLayout $ OnTabSelectedListener)'在空对象引用上

public class FragmentExplore extends Fragment {

    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;

    public FragmentExplore() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view = inflater.inflate(R.layout.fragment_explore, container, false);
        mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager());
        mViewPager = view.findViewById(R.id.viewpager);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        TabLayout tabLayout = view.findViewById(R.id.tabs);
        mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
        return view;
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int position) {
            switch (position){
                case 0:
                    FragmentExploreActivities fragmentExploreActivities = new FragmentExploreActivities();
                    return fragmentExploreActivities;
                case 1:
                    FragmentExplorePeople fragmentExplorePeople = new FragmentExplorePeople();
                    return fragmentExplorePeople;
                case 2:
                    FragmentExplorePosts fragmentExplorePosts = new FragmentExplorePosts();
                    return fragmentExplorePosts;
                case 3:
                    FragmentExploreMedia fragmentExploreMedia = new FragmentExploreMedia();
                    return fragmentExploreMedia;

            }
            return null;
        }

        @Override
        public int getCount() {
            return 4;
        }
    }
}

0 个答案:

没有答案