TabLayout使用介绍(com.google.android.material.tabs.TabLayout)

TabLayout的使用

一、控件库的导入

TabLayout是Android support中的一个控件android.support.design.widget.TabLayout,Google在升级了AndroidX之后,将TabLayout迁移到material包下面去了com.google.android.material.tabs.TabLayout,原来的support下面的TabLayout从API 29开始就不再维护了。所以如果项目已经升级了AndroidX,建议直接使用后者。这里开始使用Androidx了,引入如下:

 implementation 'com.google.android.material:material:1.2.0-alpha06'

二、基本使用

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tab" />

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tab"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:tabMode="scrollable" />
    
</androidx.constraintlayout.widget.ConstraintLayout>

主页面布局是一个ViewPager和TabLayout

TabFragment.java

public class TabFragment extends Fragment {

    public TabFragment(String str) {
        Bundle b = new Bundle();
        b.putString("key", str);
        setArguments(b);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tab, container, false);
        TextView textView = view.findViewById(R.id.text);
        textView.setText(getArguments().getString("key"));
        textView.setBackgroundColor(Color.rgb((int) (Math.random() * 255), (int) (Math.random() * 255), (int) (Math.random() * 255)));
        return view;
    }

}

TabFragment中就一个TextView,每一个fragment设置不同的label和背景颜色。

MainActivity.java

public class MainActivity extends AppCompatActivity {
    private ArrayList<Fragment> fragments = new ArrayList<>();
    private String[] titles = new String[]{"欧冠", "英超", "西甲", "意甲", "德甲", "法甲", "中超", "欧联杯", "皇马", "巴萨", "拜仁", "利物浦"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        TabLayout tabLayout = findViewById(R.id.tab);
        ViewPager viewPager = findViewById(R.id.viewpager);

        for (int i = 0; i < titles.length; i++) {
            fragments.add(new TabFragment(titles[i]));
        }

        FmPagerAdapter pagerAdapter = new FmPagerAdapter(Arrays.asList(titles), fragments, getSupportFragmentManager());
        viewPager.setAdapter(pagerAdapter);

        tabLayout.setupWithViewPager(viewPager);
    }

}

简单的分3步:

  • 找到TabLayout
  • 给ViewPager设置adapter
  • 设置TabLayout和ViewPager之间联动

运行结果:
在这里插入图片描述

  • 注意:就是在给ViewPager设置Adapter的时候,一定要重写getPageTitle(int position)方法
  • 三、TabLayout属性介绍

tabIndicatorFullWidth

设置指示器线条的宽度和文字得宽度一致,那么就可以设置tabIndicatorFullWidth属性为false,默认为true
在这里插入图片描述

tabRippleColor

点击每一个tab的时候,会出现渐变的背景色
设置 app:tabRippleColor=“@color/green”
在这里插入图片描述
如果想要去掉这个点击时的背景,可以通过设置tabRippleColor属性值为一个透明的背景色

tabTextAppearance

TabLayout并没有直接设置字体大小样式的属性,这时候就可以通过设置自定义属性tabTextAppearance来实现 app:tabTextAppearance=“@style/TextStyle”

    <style name="TextStyle">
        <item name="android:textSize">20sp</item>
        <item name="android:textStyle">bold</item>
    </style>

tabIndicatorHeight

这个属性设置指示器的高度,如果我们不需要显示指示器,则可以通过设置tabIndicatorHeight等于0来实现

tabIndicatorGravity

这个属性可以设置指示器的显示位置,可选值有bottom(默认)、center、top、stretch

stretch

在这里插入图片描述

app:tabBackground

改变整个TabLayout的颜色,直接在xml中设置:app:tabBackground=“@color/blue”。

app:tabContentStart

TabLayout中的文字内容开始位置的偏移量,自由scrollable时候有效

在这里插入图片描述
系统默认的字体开始是16dp,第二行的标签是设置app:tabContentStart="16dp"以后的情况

tabPaddingStart和tabPaddingEnd

当tabmode 是fix时候,解决tab中字体受到挤压时候字体变小问题
在这里插入图片描述
设置下面两行代码,问题就解决了:亲测有效;

        app:tabPaddingEnd="0dp"
        app:tabPaddingStart="0dp"

在这里插入图片描述

自己定义布局可以实现消息红点

在这里插入图片描述

自定义layout的item_red_dot.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        android:textAppearance="@style/tab_normal_style"
        android:textSize="17sp" />

    <View
        android:layout_width="8dp"
        android:layout_height="8dp"
        android:layout_gravity="end|top"
        android:background="@color/colorAccent" />
</FrameLayout>

java代码

public class RedDotActivity extends AppCompatActivity {

    private ArrayList<Fragment> fragments = new ArrayList<>();

    private String[] titles = new String[]{"欧冠", "英超", "西甲", "意甲", "德甲", "法甲", "中超", "欧联杯", "皇马", "巴萨", "拜仁", "利物浦"};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        TabLayout tabLayout = findViewById(R.id.tab);
        ViewPager viewPager = findViewById(R.id.viewpager);

        for (int i = 0; i < titles.length; i++) {
            tabLayout.addTab(tabLayout.newTab().setCustomView(R.layout.item_red_dot));
            fragments.add(new TabFragment(titles[i]));
        }

        for (int i = 0; i < titles.length; i++) {
            TextView view = tabLayout.getTabAt(i).getCustomView().findViewById(R.id.text1);
            view.setText(titles[i]);
        }

        FmPagerAdapter pagerAdapter = new FmPagerAdapter(Arrays.asList(titles), fragments, getSupportFragmentManager());
        viewPager.setAdapter(pagerAdapter);

        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                View customView = tab.getCustomView();
                if (customView == null) {
                    tab.setCustomView(R.layout.item_red_dot);
                }
                TextView textView = tab.getCustomView().findViewById(R.id.text1);
                textView.setTextAppearance(RedDotActivity.this, R.style.tab_select_style);
                viewPager.setCurrentItem(tab.getPosition(),true);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                View customView = tab.getCustomView();
                if (customView == null) {
                    tab.setCustomView(R.layout.item_red_dot);
                }
                TextView textView = tab.getCustomView().findViewById(R.id.text1);
                textView.setTextAppearance(RedDotActivity.this, R.style.tab_normal_style);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                tabLayout.setScrollPosition(position, positionOffset, true, true);
            }

            @Override
            public void onPageSelected(int position) {
                tabLayout.getTabAt(position).select();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

}

style内容

    <style name="tab_normal_style">
        <item name="android:textSize">15sp</item>
        <item name="android:textStyle">normal</item>
        <item name="android:textColor">@color/black</item>
    </style>

    <style name="tab_select_style">
        <item name="android:textSize">17sp</item>
        <item name="android:textStyle">bold</item>
        <item name="android:textColor">@color/green</item>
    </style>
`TabLayout` 是 Android Material Design 中用于创建标签页布局的组件。在 Android Studio 中使用 `com.google.android.material.tabs.TabLayout` 时,可以设置一系列参数来调整其外观和行为。以下是一些常用参数: 1. `app:tabMode`:设置标签页的模式,可以是 `fixed` 或 `scrollable`。`fixed` 模式下所有标签页宽度相同,而 `scrollable` 模式允许标签页根据内容宽度自动调整,超出屏幕宽度的标签页可以通过滚动查看。 2. `app:tabGravity`:设置标签页的对齐方式,可选值有 `fill` 和 `center`。`fill` 值会使得标签页均匀分布填充整个 `TabLayout`,而 `center` 值则会使得标签页居中显示。 3. `app:tabIndicatorColor`:设置标签页指示器的颜色。 4. `app:tabIndicatorHeight`:设置标签页指示器的高度。 5. `app:tabTextAppearance`:设置标签页文本的外观,可以通过引用一个文本样式来改变字体大小、颜色等。 6. `app:tabSelectedTextColor`:设置被选中的标签页文本的颜色。 7. `app:tabTextColor`:设置未被选中的标签页文本的颜色。 8. `app:tabBackground`:设置标签页的背景。 9. `app:tabPaddingStart` 和 `app:tabPaddingEnd`:设置标签页内容的左右内边距。 10. `app:tabMaxWidth`:设置标签页最大宽度。 11. `app:tabMinWidth`:设置标签页最小宽度。 12. `app:tabIndicatorAnimationDuration`:设置标签页指示器动画的持续时间。 13. `app:tabIndicatorFullWidth`:设置标签页指示器是否应该延伸到整个 `TabLayout` 的宽度。 这些参数可以通过 XML 属性设置,也可以在 Java/Kotlin 代码中通过编程方式设置。在 XML 布局文件中使用 `TabLayout` 时,通常是这样的: ```xml <com.google.android.material.tabs.TabLayout android:id="@+id/tabLayout" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabMode="fixed" app:tabGravity="fill" app:tabIndicatorColor="#FF0000" app:tabIndicatorHeight="4dp" app:tabTextAppearance="@style/MyCustomTabText" ... /> ``` 在代码中设置参数,例如: ```java TabLayout tabLayout = findViewById(R.id.tabLayout); tabLayout.setTabMode(TabLayout.MODE_FIXED); tabLayout.setTabGravity(TabLayout.GRAVITY_FILL); tabLayout.setSelectedTabIndicatorColor(Color.RED); tabLayout.setTabIndicatorHeight(4); ```
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值