项目开发的需求:实现TabLayout样式的自定义。如果单纯的修改和跳转标题的颜色及指示器的样式,可以不需要自定义;如果需要选中标题后改变字体的大小,则需要自定义tablayout样式。
1. 布局文件如下
<com.google.android.material.tabs.TabLayout
android:id="@+id/mTableLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabIndicator="@drawable/shape_indicator"
app:tabRippleColor="#00000000"
app:tabMaxWidth="200dp"
app:tabMinWidth="100dp"
app:tabTextColor="#999"
app:tabSelectedTextColor="@color/black"
app:tabIndicatorColor="@color/teal_900"
app:tabTextAppearance="@style/myTabTextAppearance"
/>
2. 增加tab_item.xml样式
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="@+id/tab_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/black"
android:textSize="20sp" />
</LinearLayout>
3. Fragement 初始化tab数据
private void initView() {
mTableLayout = (TabLayout) getActivity().findViewById(R.id.mTableLayout);
// 添加tab初始化
for (int i = 0; i < mTitles.length; i++) {
TabLayout.Tab tab = mTableLayout.newTab();
// 设置Tab的自定义View
tab.setCustomView(R.layout.tab_item);
// 添加Tab
//tab.setText(mTitles[i]);
mTableLayout.addTab(tab);
// 设置tab_item 里的文字
TextView textView = (TextView) tab.getCustomView().findViewById(R.id.tab_text);
textView.setText(mTitles[i]);//设置tab上的文字
if(i==0){
textView.setTextColor(Color.BLACK);
textView.setTextSize(18);
}else {
textView.setTextColor(Color.parseColor("#999999"));
textView.setTextSize(16);
}
}
}
4. 选中改变标题字体大小,在监听函数中实现
public void onActivityCreated(@NonNull Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Set the status bar color to transparent
initView();
mTableLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
TextView tabTextView = tab.getCustomView().findViewById(R.id.tab_text);
tabTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
tabTextView.setTextColor(ContextCompat.getColor(mContext, R.color.black));
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
TextView tabTextView = tab.getCustomView().findViewById(R.id.tab_text);
tabTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
tabTextView.setTextColor(ContextCompat.getColor(mContext, R.color.color_999));
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
5. 达到实现效果图。![](https://img-blog.csdnimg.cn/f5928654bbba417bbcb15f26ca505afb.jpeg)