style的方式只能改整体的大小,修改选中字体大小就需要用到CustomView了
效果:
核心就是给TabLayout设置自定义布局,通过自定义布局拿到id,然后设置选中时的字体大小
自定义tab布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/tab_item" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical"> <TextView android:id="@+id/tab_item_time" android:layout_width="wrap_content" android:layout_height="24dp" android:gravity="bottom" android:text="22:00" android:textColor="@drawable/selector_text_color" android:textSize="12sp"/> <TextView android:id="@+id/tab_item_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="秒杀中" android:textColor="@drawable/selector_text_color" android:textSize="12sp"/> </LinearLayout>
代码引用并设置
private void initTabView() { holder = null; for (int i = 0; i < tabs.size(); i++) { //获取tab TabLayout.Tab tab = mTabLayout.getTabAt(i); //给tab设置自定义布局 tab.setCustomView(R.layout.tab_item); holder = new ViewHolder(tab.getCustomView()); //填充数据 holder.mTabItemTime.setText(String.valueOf(tabTimes.get(i))); holder.mTabItemName.setText(tabs.get(i)); //默认选择第一项 if (i == 0) { holder.mTabItemTime.setSelected(true); holder.mTabItemName.setSelected(true); holder.mTabItemTime.setTextSize(18); holder.mTabItemName.setTextSize(12); } } mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { holder = new ViewHolder(tab.getCustomView()); holder.mTabItemTime.setSelected(true); holder.mTabItemName.setSelected(true); //设置选中后的字体大小 holder.mTabItemTime.setTextSize(18); holder.mTabItemName.setTextSize(12); //关联Viewpager mViewPager.setCurrentItem(tab.getPosition()); } @Override public void onTabUnselected(TabLayout.Tab tab) { holder = new ViewHolder(tab.getCustomView()); holder.mTabItemTime.setSelected(false); holder.mTabItemName.setSelected(false); //恢复默认字体大小 holder.mTabItemTime.setTextSize(12); holder.mTabItemName.setTextSize(12); } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } class ViewHolder { TextView mTabItemTime; TextView mTabItemName; ViewHolder(View tabView) { mTabItemTime = (TextView) tabView.findViewById(R.id.tab_item_time); mTabItemName = (TextView) tabView.findViewById(R.id.tab_item_name); } }
详见 > github:https://github.com/yechaoa/MaterialDesign 【TabLayoutCustomViewActivity】