XTabLayout.setOnTabSelectedListener不切换fragment

时间:2021-07-03 05:46:34
项目中使用XTabLayout+ViewPager实现选项卡,XTab支持定义下滑指示器的长度
<com.androidkun.xtablayout.XTabLayout
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="43dp"
    app:tabGravity="center"
    app:xTabBackgroundColor="@color/white"
    app:xTabSelectedBackgroundColor="@color/white"
    app:xTabIndicatorColor="@color/dx_blue_color"
    app:xTabIndicatorHeight="4dp"
    app:xTabIndicatorWidth="55dp"
    app:tabMinWidth="80dp"
   app:tabMode="scrollable"
   app:tabSelectedTextColor="@color/blue_color"
   app:tabTextAppearance="@style/HomeMyTablayoutTextAppearance"/>

但是发现调用setOnTabSelectedListener点击菜单时没有切换fragment,不监听则正常。查看源码发现OnTabSelectedListener中的onTabSelected方法有个默认实现:

mPageChangeListener.reset();
viewPager.addOnPageChangeListener(mPageChangeListener);

// Now we'll add a tab selected listener to set ViewPager's current item
setOnTabSelectedListener(new XTabLayout.ViewPagerOnTabSelectedListener(viewPager));
/**  * A {@link TabLayout.OnTabSelectedListener} class which contains the necessary calls back  * to the provided {@link ViewPager} so that the tab position is kept in sync.  */ public static class ViewPagerOnTabSelectedListener implements XTabLayout.OnTabSelectedListener {
    private final ViewPager mViewPager;

    public ViewPagerOnTabSelectedListener(ViewPager viewPager) {
        mViewPager = viewPager;
    }

    @Override
    public void onTabSelected(XTabLayout.Tab tab) {
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(XTabLayout.Tab tab) {
        // No-op
    }

    @Override
    public void onTabReselected(XTabLayout.Tab tab) {
        // No-op
    }
}
所以自己监听OnTabSelectedListener事件时需要在onTabSelected方法中调用ViewPager的setCurrentItem方法。
tabLayout.setOnTabSelectedListener(new XTabLayout.OnTabSelectedListener() {
    @Override
    public void onTabSelected(XTabLayout.Tab tab) {
        viewPager.setCurrentItem(tab.getPosition());
        if (tab.getPosition() == 0) {
           
        } else if (tab.getPosition() == 1) {
          
        }
    }

    @Override
    public void onTabUnselected(XTabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(XTabLayout.Tab tab) {
    }
});
可以使用addListener或者模版方法进行扩展,这样具体的set的Listener只需要关注新增监听逻辑即可。