原生TabLayout选中时如何改变字体的大小
时间: 2024-03-17 17:40:58 浏览: 23
要改变TabLayout中选中Tab的字体大小,可以通过自定义TabLayout.Tab的布局来实现。具体步骤如下:
1. 在res/layout目录下新建一个xml文件,例如:custom_tab.xml。
2. 在这个xml文件中定义一个TextView,并设置选中和未选中时的字体大小,例如:
```xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textColor="@color/tab_unselected"
android:textAppearance="@style/TextAppearance.Design.Tab" />
```
其中,android:id="@android:id/text1"是必须的,因为TabLayout会通过这个id来查找TextView,并设置Tab的文本。
3. 在TabLayout中设置自定义Tab的布局,例如:
```java
TabLayout tabLayout = findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
if (tab != null) {
tab.setCustomView(R.layout.custom_tab);
}
}
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
TextView textView = tab.getCustomView().findViewById(android.R.id.text1);
textView.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.tab_selected));
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
TextView textView = tab.getCustomView().findViewById(android.R.id.text1);
textView.setTextColor(ContextCompat.getColor(MainActivity.this, R.color.tab_unselected));
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
```
在设置Tab的布局时,使用tab.setCustomView(R.layout.custom_tab)来设置自定义的布局。
在添加Tab选中监听器时,通过tab.getCustomView().findViewById(android.R.id.text1)来获取TextView,并设置不同状态下的字体大小和颜色。例如,在onTabSelected方法中,设置字体大小为20sp,颜色为R.color.tab_selected。
注意:这里的R.color.tab_selected和R.color.tab_unselected是自定义的颜色值,可以根据自己的需求进行设置。