首页 > 解决方案 > 在 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 ://imgur.com/gallery/OYz2Z1h

标签: androidandroid-layoutandroid-tablayout

解决方案


虽然您可以在代码中设置选项卡的字体(例如字体和样式),但我发现设置文本大小的唯一方法是定义自定义选项卡视图,如下所示。

信用: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();
    }

    ...

});

推荐阅读