Android控件-TabLayout使用介绍

本文介绍了Android控件TabLayout的使用,包括它的基本功能、属性设置和实战示例。TabLayout通常与ViewPager结合使用,实现标签切换。文章详细讲解了如何设置TabLayout的属性,如tabIndicatorFullWidth、tabRippleColor等,并展示了如何动态调整Tab样式。同时,还提到了TabLayout的tabMode属性,以及如何给TabLayout设置间隔drawable。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

简述

TabLayout是Android support中的一个控件android.support.design.widget.TabLayout,Google在升级了AndroidX之后,将TabLayout迁移到material包下面去了com.google.android.material.tabs.TabLayout,原来的support下面的TabLayout从API 29开始就不再维护了。所以如果项目已经升级了AndroidX,建议直接使用后者。TabLayout一般结合ViewPager+Fragment的使用实现滑动的标签选择器。
比如新闻标签切换
在这里插入图片描述
看下TabLayout的继承关系,如下图
support包下面的
继承关系
material包下面的
在这里插入图片描述

TabLayout继承的HorizontalScrollView,所以支持左右滑动,下面写的简单的例子看看效果。

简单示例

activity_tab.xml

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

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:tabTextColor="@color/colorPrimary"
        app:tabSelectedTextColor="@color/colorPrimaryDark"
        />
    <androidx.viewpager.widget.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toBottomOf="@+id/tab_layout"
        />

</androidx.constraintlayout.widget.ConstraintLayout>

ConstraintLayout 布局里面就一个TabLayout和一个ViewPager,tabSelectedTextColor和tabTextColor属性分别设置标签选中和未选中状态的文字颜色,其他属性后面介绍。
TabFragment.java

public class TabFragment extends Fragment {
   
    public static TabFragment newInstance(String label) {
   
        Bundle args = new Bundle();
        args.putString("label", label);
        TabFragment fragment = new TabFragment();
        fragment.setArguments(args);
        return fragment;
    }
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
   
        return inflater.inflate(R.layout.fragment_tab, container, false);
    }

    @Override
    public void onStart() {
   
        super.onStart();
        String label = getArguments().getString("label");
        TextView text = getView().findViewById(R.id.tv_bg);
        text.setText(label);
        text.setBackgroundColor(Color.rgb((int)(Math.random() * 255)
评论 20
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值