TabLayout使用遇到的坑及方案
修改下划线宽度的坑效果如下: 代码实现方式: 如果想要实现这种效果,最主要控制的就是下划线部分,现在网上有很多通过反射的方式来修改下划线宽度的文章,但这段代码如果实现我们想要的效果是不可能的,因为如果研究过源码就知道Indicator的宽度跟Tab的宽度一致的,不能让指示器的宽度小于Tab的宽度,所以我们只能另辟蹊径:通过CustomView自己绘制线,通过添加OnTabSelectedListener来展示隐藏下划线,让原生的Indicaqtor高度为0也不会影响我们的展示。 OK! Talk is cheap, show me the code. 先隐藏原来的下划线,让其不显示: <android.support.design.widget.TabLayout android:id="@+id/radio_playlist_tab_layout" android:layout_width="match_parent" android:layout_height="@dimen/dp_36.7" android:background="@color/color_e8e8e8" app:tabBackground="@null" app:tabIndicatorHeight="0dp" app:tabMode="scrollable" />其次设置CustomView效果: 再手动控制切换时Tab的下划线:mTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener { override fun onTabReselected(tab: TabLayout.Tab?) { val view = tab?.customView?.findViewById<View>(R.id.tab_indicator) val textView = tab?.customView?.findViewById<TextView>(R.id.tab_tv_date) textView?.setTextColor(mTabSelectedColor) view?.visibility = View.VISIBLE } override fun onTabUnselected(tab: TabLayout.Tab?) { val view = tab?.customView?.findViewById<View>(R.id.tab_indicator) val textView = tab?.customView?.findViewById<TextView>(R.id.tab_tv_date) textView?.setTextColor(mTabUnSelectedColor) view?.visibility = View.INVISIBLE } override fun onTabSelected(tab: TabLayout.Tab?) { val view = tab?.customView?.findViewById<View>(R.id.tab_indicator) val textView = tab?.customView?.findViewById<TextView>(R.id.tab_tv_date) textView?.setTextColor(mTabSelectedColor) view?.visibility = View.VISIBLE } }) 间距部分只是这样的话,下划线的问题解决了。但对于我们的UI对于界面还原度要求较高,对于Tab之间的间距也有一些要求,所以也要处理,对于间距部分的处理可以按照之前的方式通过反射来完成。注意,这种方式因为需要计算TextView的文字宽度,所以要放到设置完所有的customView后调用。 ...