0
点赞
收藏
分享

微信扫一扫

Android TabLayout的自定义Tab

九月的栩 2022-02-23 阅读 81

实现效果如下图:
在这里插入图片描述
上代码:
xml

<com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="0dp"
        android:layout_height="35dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:background="@drawable/bg_tab"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:tabBackground="@color/transparent"
        app:tabGravity="fill"
        app:tabIndicatorHeight="0dp"
        app:tabMode="fixed"
        app:tabPaddingBottom="-1dp"
        app:tabPaddingEnd="-1dp"
        app:tabPaddingStart="-1dp"
        app:tabPaddingTop="-1dp"
        app:tabRippleColor="@color/transparent" />
    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager"
        android:background="#f0f0f0"
        app:layout_constraintTop_toBottomOf="@+id/tabLayout"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:layout_width="0dp"
        android:layout_height="0dp"/>
bg_tab_sel
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_selected="true" android:drawable="@drawable/bg_cell_tab_sel"/>
    <item android:state_selected="false" android:drawable="@color/grey_eeeeee" />
</selector>

bg_tab
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="5dp"/>
    <solid android:color="@color/grey_eeeeee"/>
</shape>

bg_cell_tab_sel
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="5dp"/>
    <solid android:color="@color/white"/>
</shape>

activity:

fragmentList= arrayListOf(OneFragment(),TwoFragment())
        viewPager.adapter = object: FragmentStateAdapter(this){
            override fun getItemCount(): Int {
                return fragmentList.size
            }

            override fun createFragment(position: Int): Fragment {
                return fragmentList[position]
            }

        }
        //主要是用这个方法
        TabLayoutMediator(tabLayout,viewPager){tab, position ->
            var view = LayoutInflater.from(this).inflate(R.layout.tab_cell,tab.parent,false)
            view.tabTitleTv.text = titleList!![position]
            tab.customView = view
        }.attach()
        viewPager.offscreenPageLimit = fragmentList.size - 1
    }

普通的tablayout实现起来比较麻烦,但是升级后的com.google.android.material.tabs.TabLayout就很棒,实现其他效果也很方便~

举报

相关推荐

0 条评论