如何修改TabLayoutPlus的字体大小?自定义样式未生效问题咨询
解决TabLayoutPlus文本尺寸无法修改的问题
我之前也碰到过类似的问题,TabLayoutPlus这类自定义控件有时候确实不会乖乖响应常规的样式设置,给你几个靠谱的解决办法:
方法一:直接使用库的自定义属性设置
首先试试直接在布局XML里给TabLayoutPlus添加文本大小的属性,很多自定义库都会提供这类属性。记得先确保布局头部引入了xmlns:app="http://schemas.android.com/apk/res-auto",不然app:开头的属性会报错。
示例布局代码:
<cn.mycommons.tablayoutplus.library.TabLayoutPlus android:id="@+id/fullSearch_tabLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/fullSearch_toolbar" android:background="@color/your_background_color" app:tabTextSize="14sp" /> <!-- 这里替换成你想要的字体大小 -->
方法二:通过自定义TextAppearance样式覆盖
如果直接设置属性没效果,试试定义一个文本样式,然后让TabLayoutPlus使用这个样式。
在styles.xml里添加自定义样式:
<style name="CustomTabTextStyle" parent="TextAppearance.AppCompat.Widget.ActionBar.Title.Inverse"> <item name="android:textSize">14sp</item> <!-- 还可以顺便设置文本颜色等其他样式 --> <item name="android:textColor">@color/your_text_color</item> </style>
然后在布局里给TabLayoutPlus指定这个样式:
app:tabTextAppearance="@style/CustomTabTextStyle"
方法三:代码动态修改文本大小
如果XML方式都不生效,那就用代码直接找到Tab里的文本控件修改,这种方式比较直接粗暴但有效:
TabLayoutPlus tabLayout = findViewById(R.id.fullSearch_tabLayout); for (int i = 0; i < tabLayout.getTabCount(); i++) { TabLayoutPlus.Tab tab = tabLayout.getTabAt(i); if (tab != null) { // 处理默认TabView的情况 if (tab.getCustomView() == null) { View tabView = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(i); if (tabView instanceof TextView) { ((TextView) tabView).setTextSize(TypedValue.COMPLEX_UNIT_SP, 14); } } // 处理自定义TabView的情况(如果之前设置过自定义布局) else { TextView textView = tab.getCustomView().findViewById(R.id.tab_text); if (textView != null) { textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14); } } } }
方法四:完全自定义Tab布局(最灵活)
如果上面的方法都不行,那就彻底自定义每个Tab的布局,这样你能完全控制文本的所有样式:
- 先创建一个自定义Tab布局文件
layout_custom_tab.xml:
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/tab_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="14sp" android:textColor="@color/tab_text_selector" <!-- 可以用selector实现选中/未选中颜色变化 --> android:gravity="center" android:paddingVertical="8dp" />
- 然后在代码里给每个Tab设置这个自定义布局:
TabLayoutPlus tabLayout = findViewById(R.id.fullSearch_tabLayout); // 先添加标签 tabLayout.addTab(tabLayout.newTab().setText("搜索结果")); tabLayout.addTab(tabLayout.newTab().setText("热门推荐")); // 遍历设置自定义布局 LayoutInflater inflater = LayoutInflater.from(this); for (int i = 0; i < tabLayout.getTabCount(); i++) { TabLayoutPlus.Tab tab = tabLayout.getTabAt(i); if (tab != null) { View customTabView = inflater.inflate(R.layout.layout_custom_tab, null); TextView tabText = customTabView.findViewById(R.id.tab_text); tabText.setText(tab.getText()); tab.setCustomView(customTabView); } }
内容的提问来源于stack exchange,提问作者RedBounce
相关产品推荐
相关产品推荐

