Android TabLayout 实现随意控制item之间的间距

效果

红色标注是不同的间距。

实现方式

1、xml中定义

kotlin 复制代码
       <com.google.android.material.tabs.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="wrap_content"
            app:tabIndicatorColor="@color/color_FF00B2E3"
            app:tabBackground="@android:color/transparent"
            app:tabRippleColor="@android:color/transparent"
            android:layout_height="wrap_content"
            app:tabIndicatorHeight="5dp"
            android:background="@android:color/transparent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent">
        </com.google.android.material.tabs.TabLayout>

2、代码动态添加自定义tab

kotlin 复制代码
        for (int i = 0; i < mTabsStrId.length; i++) {
            View tabview = LayoutInflater.from(getContext()).inflate(R.layout.tab_item, null);
            TextView tvTab = tabview.findViewById(R.id.tv_tab);
            tvTab.setText(mTabsStrId[i]);
            TabLayout.Tab tab = binding.tabLayout.newTab();
            tab.setCustomView(tabview);
            binding.tabLayout.addTab(tab, i == 0);
        }

tab的xml布局

kotlin 复制代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_tab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:includeFontPadding="false"
        android:textFontWeight="500"
        android:text="@string/xxx"
        android:textColor="@color/selector_xxx"
        android:textSize="28sp" />
</LinearLayout>

3、去除tablayout原有padding,并设置两个tab之间的间距

kotlin 复制代码
        for (int i = 0; i < binding.tabLayout.getTabCount(); i++) {
            View tab = ((ViewGroup) binding.tabLayout.getChildAt(0)).getChildAt(i);
            ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) tab.getLayoutParams();
            tab.setPadding(0, 0, 0, 0);
            if (i > 0) {
                params.setMargins(DisplayUtils.dp2px(86), 0, 0, 0); // 设置左右间距
            } else {
                params.setMargins(DisplayUtils.dp2px(22), 0, 0, 0); // 设置左右间距
            }
        }
        binding.tabLayout.invalidate();
相关推荐
只因只因爆14 分钟前
如何在idea中写spark程序
java·spark·intellij-idea
你憨厚的老父亲突然20 分钟前
从码云上拉取项目并在idea配置npm时完整步骤
java·npm·intellij-idea
全栈凯哥32 分钟前
桥接模式(Bridge Pattern)详解
java·设计模式·桥接模式
PXM的算法星球35 分钟前
【软件工程】面向对象编程(OOP)概念详解
java·python·软件工程
两点王爷36 分钟前
springboot项目文件上传到服务器本机,返回访问地址
java·服务器·spring boot·文件上传
小吕学编程38 分钟前
ES练习册
java·前端·elasticsearch
qsmyhsgcs1 小时前
Java程序员转人工智能入门学习路线图(2025版)
java·人工智能·学习·机器学习·算法工程师·人工智能入门·ai算法工程师
云心似我心^o^4051 小时前
使用POI和EasyExcel使用导入
java
我是大头鸟1 小时前
SpringMVC 使用thymeleaf 进行数据展示
java·springmvc·thymeleaf
小刘|1 小时前
JVM 自动内存管理
java·jvm·算法