前言

Android 开发中TabLayout 是一个非常常用的控件,而且许多情况下Tablayout中的indicator款式也会做一些修正而不是用自带的Theme款式,这篇文章主要便是记载一下如何自定义款式以及基本的运用


基本运用

首先TabLayout是能够直接在XML中创立TabItem的,可是日常的运用情况下都是依据数据源或许与ViewPager2等控件一同联动运用,然后依据数据源或许ViewPager2的标题进行动态的设置TabItem。 

XML静态设置TabItem

<com.google.android.material.tabs.TabLayout
    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">
    <com.google.android.material.tabs.TabItem
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Tab1" />
    <com.google.android.material.tabs.TabItem
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Tab3" />
    <com.google.android.material.tabs.TabItem
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Tab2" />
</com.google.android.material.tabs.TabLayout>

xml_use.png


接下来便是依据Tablayout获取TabItem然后做一系列操作,这儿就不演示了

联动ViewPager2动态设置TabItem

本篇文章只记载ViewPager2联动TabLayout,ViewPager联动起来也大差不差

1. Activity布局代码

<com.google.android.material.tabs.TabLayout
    android:id="@+id/tabLayout"
    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" />
<androidx.viewpager2.widget.ViewPager2
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/tabLayout" />

2. 创立三个Fragment给ViewPager2设置

project_fragment.png

3. 每个Fragment对应的XML布局能够自行发挥,这儿我就直接运用居中TextView。

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".fragment.FirstFragment">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="First"
        android:textColor="@color/black"
        android:textSize="20sp" />
</FrameLayout>

4. 绑定起来

Activity代码

class MainActivity : AppCompatActivity(R.layout.activity_main) {
    private val tabLayout: TabLayout by lazy { findViewById(R.id.tabLayout) }
    private val pager: ViewPager2 by lazy { findViewById(R.id.pager) }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        pager.adapter = MyPagerAdapter(this)
        // 联动
        TabLayoutMediator(tabLayout, pager) { tab, position ->
            when (position) {
                0 -> tab.text = "First"
                1 -> tab.text = "Second"
                2 -> tab.text = "Third"
            }
        }.attach()
    }
}
class MyPagerAdapter(fActivity: FragmentActivity) :
    androidx.viewpager2.adapter.FragmentStateAdapter(fActivity) {
    override fun getItemCount() = 3
    override fun createFragment(position: Int) = when (position) {
        0 -> FirstFragment()
        1 -> SecondFragment()
        2 -> ThirdFragment()
        else -> FirstFragment()
    }
}

终究作用

2022-09-09 10-17-33.2022-09-09 10_18_18.gif


依据数据源动态生成TabItem

这一种运用方式也是非常常用的,有时分一个商品的分类,能够把类别标题渲染到TabLayout的TabItem中,然后**依据TabLayout选中了哪个TabItem去恳求选中类别的数据*

1.Activity布局代码

为了方便这儿就不联动RecyclerView进行演示了,直接用一个TextView,当点击了TabLayout中的TabItem改变TextView文字标题。感兴趣能够自行进行扩展。

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout"
        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" />
    <TextView
        android:id="@+id/title_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/black"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tabLayout" />
</androidx.constraintlayout.widget.ConstraintLayout>

2. Activity代码

class MainActivity : AppCompatActivity(R.layout.activity_main) {
    private val data = ArrayList<String>().apply {
        for (i in 0 until 40) {
            add("Item ${i + 1}")
        }
    }
    private val tabLayout: TabLayout by lazy { findViewById(R.id.tabLayout) }
    private val title: TextView by lazy { findViewById(R.id.title_tv) }
    private var currentPosition = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        data.forEach {
            tabLayout.addTab(tabLayout.newTab().setText(it))
        }
        title.text = data[currentPosition]
        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                tab?.let {
                    currentPosition = it.position
                    title.text = data[currentPosition]
                }
            }
            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }
            override fun onTabReselected(tab: TabLayout.Tab?) {
            }
        })
    }
}

终究作用

2022-09-09 11-02-54.2022-09-09 11_03_52.gif


修正TabLayout背景色彩

TabLayout的背景色彩默许是白色的,能够经过修正父布局的背景色彩看出来

QQ20220909-112044@2x.png

调用特点background就能够修正,我这儿修正成蓝色,要修正成透明也相同直接设置就ok

<com.google.android.material.tabs.TabLayout
    android:id="@+id/tabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#03A9F4"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

QQ20220909-112827@2x.png

修正indicator

自定义Indicator款式能够运用layer-list,修正TabItem的字体能够运用Theme,简单的款式修正能够经过自带的特点进行完成。

layer-list

layer-list 是DrawableResource的一种。能够经过它对indicator完成设置边距,形状(圆角矩形 圆形),宽度以及高度

制作圆形的indicator

许多时分indicator的形状不是简单的一条横线,有各式各样的形状,这儿就以圆形举例,创立一个layer-list文件然后在TabLayout的tabIndicator特点设置上去就能够了

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 注意设置gravity为center,因为默许左对齐 -->
    <item android:gravity="center">
        <shape android:shape="oval">
            <size
                android:width="4dp"
                android:height="4dp" />
        </shape>
    </item>
</layer-list>
<com.google.android.material.tabs.TabLayout
    android:id="@+id/tabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabIndicator="@drawable/indicator_circle_shape">

终究作用便是这样,点击的时分也相同支持滑动的动画作用
image.png

制作圆角矩形indicator

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape>
            <corners android:radius="4dp" />
            <size android:height="4dp" />
        </shape>
    </item>
</layer-list>
<com.google.android.material.tabs.TabLayout
    android:id="@+id/tabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabIndicatorFullWidth="false"
    app:tabIndicator="@drawable/indicator_full_tab_shape">

终究作用

image.png

注意

layer-list里面设置色彩是无效的,假如需要设置色彩能够直接在TabLayout的tabIndicatorColor设置色彩

修正边距

直接在layer-list文件中指定一下 left right top bottom 特点就能够

这儿设置间隔底部8dp

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:bottom="8dp">
        <shape>
            <corners android:radius="4dp" />
            <size android:height="4dp" />
        </shape>
    </item>
</layer-list>

就会发现间隔文字近了一点,left 和 right 的运用也很简单,指定好就行

终究作用
image.png

修正tabBackground

光经过修正indicator许多时分还满意所有的需求,比如有时分需要这种款式只修正indicator也能达到,指定下高度以及形状就ok,可是其实还有更好的办法便是运用tabBackground

image.png

完成上图作用能够写一个selector文件,最终修正文字色彩即可

注意: 在运用selector修正tabBackground的时分能够在当中修正色彩,这一点和修正indicator有差别

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true">
        <shape>
            <solid android:color="@color/design_default_color_primary" />
        </shape>
    </item>
    <item android:state_selected="false">
        <shape>
            <solid android:color="@android:color/transparent" />
        </shape>
    </item>
</selector>
<com.google.android.material.tabs.TabLayout
    android:id="@+id/tabLayout"
    app:tabSelectedTextColor="@color/white"
    app:tabTextColor="#C6C6C6"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabBackground="@drawable/tab_bg">

假如想要添加圆角直接在selector中指定即可,假如要做成描边也相同

image.png

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true">
        <shape>
            <stroke android:width="1dp" android:color="@color/design_default_color_primary" />
        </shape>
    </item>
    <item android:state_selected="false">
        <shape>
            <solid android:color="@android:color/transparent" />
        </shape>
    </item>
</selector>
<com.google.android.material.tabs.TabLayout
    android:id="@+id/tabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabBackground="@drawable/tab_bg"

修正文字

tab的文字默许是全大写,能够自己写一个style然后设置tabTextAppearance特点中即可,或许修正文字大小也是相同的操作

<style name="MyTabTextStyle" parent="@android:style/TextAppearance.Widget.TabWidget">
    <item name="textAllCaps">false</item>
    <item name="android:textSize">20sp</item>
</style>
<com.google.android.material.tabs.TabLayout
    android:id="@+id/tabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabBackground="@drawable/tab_bg"
    app:tabTextAppearance="@style/MyTabTextStyle">

终究作用

image.png


最终谢谢阅览