1.项目中遇到了需要TabLayout+ViewPager实现切换tab联动的效果,因为需要改变tab的宽度,而design包里的tabLayout默认是不能改变的,所以需要自己定义一个。
2.自定义XTabLayout,介绍一下属性的作用
<com.yhy.view.widget.tablayout.XTabLayout
android:id="@+id/tablayout"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/p_248_248_248"
app:xTabIndicatorHeight="0dp" //移动游标的高度,设置为0就是不显示游标
app:xTabIndicatorColor="@color/appthemecolor" //设置移动游标的颜色
app:xTabMode="scrollable" //设置tablayout的展示模式,两种 1.fixed是全屏显示不可滚动 2.可以滑动显示
app:xTabTextSize="15sp" //设置tab的字体大小
app:xTabPadding="5dp" //设置两个tab之前的间距
app:xTabMaxWidth="200dp" //设置tab的最大宽度
app:xTabMinWidth="48dp" //设置tab的最小宽度
app:xTabSelectedTextSize="17sp" //设置tab选中的字体大小
app:xTabSelectedTextColor="@color/appthemecolor"//设置tab选中的字体颜色
app:xTabTextColor="@color/p_170_170_170"> //设置tab默认的字体颜色
</com.yhy.view.widget.tablayout.XTabLayout>
3.如果默认的tabLayout的tab样式不能够满足开发需要,我们也是可以自定义的,具体方式:
XTabLayout.Tab tab = tabLayout.getTabAt(i);//获得每一个tab
tab.setCustomView(R.layout.tab_item);//给每一个tab设置view
if (i == 0) {
// 设置第一个tab的TextView是被选择的样式
tab.getCustomView().findViewById(R.id.tab_item).setSelected(true);//第一个tab被选中
}
TextView textView = (TextView) tab.getCustomView().findViewById(R.id.tab_title);
textView.setText(titles[i]);//设置tab上的文字
4.监听
tabLayout.setOnTabSelectedListener(new XTabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(XTabLayout.Tab tab) {
tab.getCustomView().findViewById(R.id.tab_item).setSelected(true);
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(XTabLayout.Tab tab) {
tab.getCustomView().findViewById(R.id.tab_item).setSelected(false);
}
@Override
public void onTabReselected(XTabLayout.Tab tab) {
}
});
5.demo源码
点击打开链接 https://download.youkuaiyun.com/download/yhy123456q/10354972