如上图,tabLayout在选中时改变文字大小。
贴下出问题的代码
test.xml布局
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/black"
android:layout_gravity="center"
android:text="123"
android:textColor="@color/white"
android:textSize="30px" />
</FrameLayout>
TabLayoutMediator mediator = new TabLayoutMediator(tabLayout, viewPager2, true, new TabLayoutMediator.TabConfigurationStrategy() {
@Override
public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.test, null, false);
tab.setCustomView(view);
}
});
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
ViewGroup view = (ViewGroup) tab.getCustomView();
TextView tv1 = (TextView) view.getChildAt(0);
tv1.setTextSize(50f);//为了方便测试,随便写个大小
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
ViewGroup view = (ViewGroup) tab.getCustomView();
TextView tv1 = (TextView) view.getChildAt(0);
tv1.setTextSize(30f);
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
mediator.attach();
上面这种写法,会导致左右滑动indicator切换发生跳闪,原因是TextView.setTextSize会导致requestLayout(),造成动画重新开始
下面给出其中一种解决方法,套两个textview 上代码test.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/black"
android:layout_gravity="center"
android:text="123"
android:textColor="@color/white"
android:textSize="24sp"
android:visibility="invisible" />
<TextView
android:id="@+id/tv_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/black"
android:layout_gravity="center"
android:text="456"
android:textColor="@color/white"
android:textSize="20sp" />
</FrameLayout>
//其他部分一样,就不重新贴了
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
ViewGroup view = (ViewGroup) tab.getCustomView();
TextView tv1 = (TextView) view.getChildAt(0);
TextView tv2 = (TextView) view.getChildAt(1);
tv1.setVisibility(View.VISIBLE);
tv2.setVisibility(View.INVISIBLE);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
int position = tab.getPosition();
ViewGroup view = (ViewGroup) tab.getCustomView();
TextView tv1 = (TextView) view.getChildAt(0);
TextView tv2 = (TextView) view.getChildAt(1);
tv1.setVisibility(View.INVISIBLE);
tv2.setVisibility(View.VISIBLE);
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});