TabLayout使用笔记

423 阅读1分钟

TabLayout设置竖向间隔线

效果图效果图

image.png

实现代码实现代码

private fun addDivider() {
    val linearLayout = binding.tabLayout.getChildAt(0) as LinearLayout
    linearLayout.let {
        it.showDividers = LinearLayout.SHOW_DIVIDER_MIDDLE
        it.dividerDrawable =
            ContextCompat.getDrawable(requireActivity(), R.drawable.shape_tab_divider)
        it.dividerPadding = 30
    }
}

定义drawable R.drawable.shape_tab_divider

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

    <solid android:color="@color/purple_200"/>
    <size android:width="1dp" android:height="10dp"/>
</shape>

TabLayout设置指示器样式

效果图1

image.png

实现代码

  1. 在drawable定义样式文件 shape_tab_indicator
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:width="15dp"
        android:height="5dp"
        android:gravity="center">
        <shape>
            <corners android:radius="5dp" />
            <solid android:color="@color/purple_500" />
        </shape>
    </item>
</layer-list>

2. 在布局文件中引入 app:tabIndicator="@drawable/shape_tab_indicator" 如下:

image.png


效果图2

image.png

代码实现 定义两个drawable

  1. shape_tab_bg.xml tablayout的圆形背景
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">


    <corners android:radius="999dp"/>
    <solid android:color="@color/purple_200"/>
</shape>

2. shape_full_tab_indicator.xml 选中的指示器的背景

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:gravity="center" android:top="0.5dp" android:bottom="0.5dp">
        <shape>
            <size android:height="41dp"/>
            <corners android:radius="999dp" />
            <solid android:color="@color/white"/>
        </shape>
    </item>
</layer-list>

在布局中引入如下

image.png

说明一下:设置

app:tabIndicatorGravity="center" 指示器才能在正中间
app:tabIndicatorColor="@android:color/transparent" 背景设为透明,tabIndicator设置的颜色才会生效

设置角标

效果图

image.png

实现代码如下

private fun setBadge(){
    val badge = binding.tabLayout.getTabAt(1)?.orCreateBadge
    badge?.number = 1//设置数字
    badge?.backgroundColor = ContextCompat.getColor(requireContext(), R.color.teal_700)//设置背景颜色
    badge?.badgeTextColor = ContextCompat.getColor(requireContext(), R.color.white)//设置文本颜色
}

private fun setBadge1(){
    val badge = binding.tabLayout.getTabAt(2)?.orCreateBadge
    badge?.backgroundColor = ContextCompat.getColor(requireContext(), R.color.red)
}