问题描述
因此,我具有带有两个TabItem的TabLayout。我希望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://imgur.com/gallery/OYz2Z1h
解决方法
虽然您可以在代码中设置标签的字样(例如,字体和样式),但我发现设置文本大小的唯一方法是定义如下所示的自定义标签视图。
信用: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();
}
...
});