选项卡布局如果在PageChangedListener中使用Viewpager notifyDataChanged,则选项卡不会滚动到选定位置

时间:2019-12-19 09:43:54

标签: android-viewpager android-tablayout notifydatasetchanged

我已将TabLayout设置为ViewPager。我正在动态设置选项卡,我的TabLayout中有大约20多个选项卡。如果选择了某些选项卡,该选项卡在屏幕上不可见的TabView的最右侧,则将加载选项卡的内容,但选项卡不会滚动到所选位置。

中的TabLayout和ViewPager代码
 TabLayout tabLayout;
    ViewPager viewPager;

tabLayout = v.findViewById(R.id.tabs);
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        viewPager = v.findViewById(R.id.viewpager);
        viewPager.setOffscreenPageLimit(1);
  tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
 adapter = new RestCatMenuAdapter(getActivity().getSupportFragmentManager(), restTab.size());
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager,true);
        viewPager.setCurrentItem(1);
        tabLayout.getTabAt(0).setIcon(R.drawable.search_icon);  

我的TabLayout tabSelectedListener和onPageChangeListener的代码是

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                viewPager.getAdapter().notifyDataSetChanged();
                viewPager.setCurrentItem(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
                imm.hideSoftInputFromWindow(tabLayout.getWindowToken(), 0);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                imm.hideSoftInputFromWindow(tabLayout.getWindowToken(), 0);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                imm.hideSoftInputFromWindow(tabLayout.getWindowToken(), 0);
            }
        });

在此,我使用了viewPager.getAdapter().notifyDatahanged()在VewPager上刷新了RecyclerView。如何解决呢?

0 个答案:

没有答案