TabLayout scrolls to unkown position after calling notifyDataSetChanged on PagerAdapter

后端 未结 5 1188
死守一世寂寞
死守一世寂寞 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 19:53

    I just added notifyDataSetChanged method inside of TabLayout implementation of Rasi.

    It works for me.

    public class CustomTabLayout extends TabLayout {
    
    /*
       * Variable to store invalid position.
       */
    private static final int INVALID_TAB_POS = -1;
    
    /*
    * Variable to store last selected position, init it with invalid tab position.
    */
    private int mLastSelectedTabPosition = INVALID_TAB_POS;
    
    public CustomTabLayout(Context context) {
        super(context);
    }
    
    public CustomTabLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    
    public CustomTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    
    @Override
    public void removeAllTabs() {
        // Retain last selected position before removing all tabs
        mLastSelectedTabPosition = getSelectedTabPosition();
        super.removeAllTabs();
    }
    
    @Override
    public int getSelectedTabPosition() {
        // Override selected tab position to return your last selected tab position
        final int selectedTabPositionAtParent = super.getSelectedTabPosition();
        return selectedTabPositionAtParent == INVALID_TAB_POS ?
                mLastSelectedTabPosition : selectedTabPositionAtParent;
    }
    
    public void notifyDataSetChanged() {
        post(new Runnable() {
            @Override
            public void run() {
                TabLayout.Tab selectedTab = getTabAt(getSelectedTabPosition());
                if (selectedTab != null) {
                    selectedTab.select();
                }
            }
        });
    }
    }
    

    and to notify call

    mPagerAdapter.notifyDataSetChanged();
    mCustomTabLayout.notifyDataSetChanged();
    

提交回复
热议问题