android - 在 TabLayout android 中更改文本的大小
问题描述
所以我有 TabLayout,里面有两个 TabItems。我希望 TabLayout 内的文本增加,并且当我从第一个选项卡滑动到另一个选项卡时,我希望它像第一个选项卡内的文本变小并且另一个选项卡内的文本大小增加一样对其进行动画处理。
我的 TabLayout 监听器:
final TabLayout tablayout=(TabLayout)rootview.findViewById(R.id.TabLayout);
final ViewPager viewPager=rootview.findViewById(R.id.MainActivityPager);
final TabLayoutAdapter tabLayoutAdapter=new TabLayoutAdapter(getContext(),getChildFragmentManager(),2);
viewPager.setAdapter(tabLayoutAdapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tablayout));
tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
tabLayoutAdapter.notifyDataSetChanged();
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
解决方案
虽然您可以在代码中设置选项卡的字体(例如字体和样式),但我发现设置文本大小的唯一方法是定义自定义选项卡视图,如下所示。
信用:https ://stackoverflow.com/a/46972634/6400636
创建名为custom_tab.xml 的XML 布局
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/text1"
android:textColor="?android:attr/textColorPrimary"/>
代码:
// Set a custom view for your tab(s)
TextView customTabView = (TextView) this.getLayoutInflater().inflate(R.layout.custom_tab, null);
tab.setCustomView(customTabView);
tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
tabLayoutAdapter.notifyDataSetChanged();
// Larger font size on select
TextView customTabView = (TextView) tab.getCustomView();
customTabView.setTextSize(24f);
// or animate
customTabView.setPivotX(0f);
customTabView.animate()
.scaleX(1.5f)
.setInterpolator(LinearInterpolator())
.setDuration(500)
.start();
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
// Smaller font size on unselect
TextView customTabView = (TextView) tab.getCustomView();
customTabView.setTextSize(18f);
customTabView.setPivotX(0f);
customTabView.animate()
.scaleX(1f)
.setInterpolator(LinearInterpolator())
.setDuration(500)
.start();
}
...
});
推荐阅读
- ios - 默认 UIFont 大小和重量,但也支持 preferredFontForTextStyle
- primes - 带有 TLA+ 的 isPrime 函数
- javascript - 在JS中从字符串中查找特定文本的最有效方法?
- python - For循环覆盖外部变量而不是创建新变量
- spring - 有没有办法将 Retrofit @QueryMap 映射到 Spring Rest 服务的某个对象?
- c - 如何扫描C中的最后两位数字?
- php - PHP PDO:调用函数后对象自动解构
- c# - 了解使用 Windows 本机 WPF 客户端登录 ADFS
- apache-spark - Jupyter 上的 pyspark 内核生成“未找到火花”错误
- macos - 无法从主机访问 Docker swarm 中的 Web 服务器