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();
相关推荐
泉城老铁5 分钟前
windows服务器mysql数据库备份脚本
java·后端·mysql
神奇的板烧8 分钟前
Java泛型不变性引发的类型转换问题及解决方案
java·c#
Apeng_09199 分钟前
ui-picture-bd-marker实现图片标注功能
ui·vue
悦悦子a啊30 分钟前
[Java]实验--编写TCP客户端程序
java·tcp/ip·php
BBB努力学习程序设计39 分钟前
Java循环:让代码重复工作的"魔法"
java
伐尘1 小时前
【MySQL】MySQL 有效利用 profile 分析 SQL 语句的执行过程
android·sql·mysql
青云交1 小时前
Java 大视界 -- Java 大数据在智能交通智能停车诱导与车位共享中的应用
java·智能停车·故障预测·极端气候适配·车位共享·民生应用·政企协同
從南走到北1 小时前
JAVA代驾小程序源码代驾跑腿APP源码
java·开发语言·微信·微信小程序·小程序
Haha_bj1 小时前
七、Kotlin——扩展(Extensions)
android·kotlin