美文网首页
TabLayout 自定义

TabLayout 自定义

作者: 天青色等Y雨 | 来源:发表于2024-03-13 18:20 被阅读0次
    实现效果
    一、依赖配置
    dependencies {
           api("com.google.android.material:material:1.11.0")
    }
    
    二、使用
    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="32dp"
        app:tabBackground="@null"                               // 去除点击时水波纹效果
        app:tabIndicator="@drawable/layer_tab_indicator"        // 自定义指示器
        app:tabIndicatorColor="@color/colorAccent"
        app:tabMode="scrollable"                                // 设置Tab可滚动
        app:tabRippleColor="@null" />                           // 去除点击时水波纹效果
    
    layer_tab_indicator.xml
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:gravity="center">
            <shape>
                <size
                    android:width="16dp"
                    android:height="3dp" />
                <solid android:color="@color/colorAccent" />
                <corners android:radius="9dp" />
            </shape>
        </item>
    </layer-list>
    
    代码
    mTabTitles.forEach {
        val tabView = LayoutInflater.from(mActivity).inflate(R.layout.item_order_tab, null)
        tabView.findViewById<TextView>(R.id.tv_tab).text = it
        mTabLayout?.addTab(mTabLayout!!.newTab().setCustomView(tabView))
    }
    mTabLayout?.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
        override fun onTabSelected(tab: TabLayout.Tab?) {
            // Others
            tab?.view?.findViewById<TextView>(R.id.tv_tab)?.setTextColor(Color.BLACK)
        }
    
        override fun onTabUnselected(tab: TabLayout.Tab?) {
            tab?.view?.findViewById<TextView>(R.id.tv_tab)
                        ?.setTextColor(resources.getColor(R.color.color9A9A9A, null))
        }
    
        override fun onTabReselected(tab: TabLayout.Tab?) {}
    })
    
    item_order_tab.xml
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="wrap_content"
        android:layout_height="32dp">
    
        <TextView
            android:id="@+id/tv_tab"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:textSize="14sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    相关文章

      网友评论

          本文标题:TabLayout 自定义

          本文链接:https://www.haomeiwen.com/subject/yslizdtx.html