TabLayout scrolls to unkown position after calling notifyDataSetChanged on PagerAdapter

后端 未结 5 1191
死守一世寂寞
死守一世寂寞 2021-02-14 19:23

I have sample project with TabLayout and PagerAdapter. Strange things happens with TabLayout when I call pagerAdapter.notifyDataSetChanged();

5条回答
  •  迷失自我
    2021-02-14 20:08

    I fix the issue, you need modify the TabLayout source code

    void populateFromPagerAdapter() {
        removeAllTabs();
    
        if (mPagerAdapter != null) {
            final int adapterCount = mPagerAdapter.getCount();
            for (int i = 0; i < adapterCount; i++) {
                addTab(newTab().setText(mPagerAdapter.getPageTitle(i)), false);
            }
    
            // need call post to run the code, to fix children views not layout
            post(new Runnable() {
                @Override
                public void run() {
                    // Make sure we reflect the currently set ViewPager item
                    if (mViewPager != null && adapterCount > 0) {
                        final int curItem = mViewPager.getCurrentItem();
                        if (curItem != getSelectedTabPosition() && curItem < getTabCount()) {
                            selectTab(getTabAt(curItem));
                        }
                    }
                }
            });
        }
    }
    

提交回复
热议问题