zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

Android设置TabLayout熟悉及下划线宽度

Android 设置 熟悉 宽度 下划线 TabLayout
2023-06-13 09:13:11 时间

Tablayout的使用 属性

app:tabMod 设置Tab模式 app:tabTextColor 设置文本颜色 app:tabSelectedTextColor 设置选中文本颜色 app:tabIndicatorColor 设置下滑条颜色 app:tabMaxWidth=“xxdp” 设置最大的tab宽度 app:tabMinWidth=“xxdp” 设置最小的tab宽度

动态创建(使用java代码添加tab) val fruitList = listOf(“Tab1”,“Tab2”,“Tab3”,“Tab4”,“Tab5”) 先是通过findviewbyid方法找到实例,之后调用tablayout的newTab方法来创建tab

		with(mTabLayout) {
            this?.addTab(tabLayout.newTab().setText(fruitList[0]));
            this?.addTab(tabLayout.newTab().setText(fruitList[1]));
            this?.addTab(tabLayout.newTab().setText(fruitList[2]));
            this?.addTab(tabLayout.newTab().setText(fruitList[3]))
            this?.addTab(tabLayout.newTab().setText(fruitList[3]))
        };

不过,使用动态的话,如果不设置相关的属性,是不能达到两个选项各自占长度一半,还得给Tablayout加上下列属性

app:tabMaxWidth="0dp"
 app:tabGravity="fill"
app:tabMode="fixed"

Tablayout与Viewpager联用 一句代码即可搞定 tabLayout!!.setupWithViewPager(viewPager) 有些时候可能会出现不显示文本的情况,这时候需要在 PagerAdapter 里面重写一个方法

@Override
public CharSequence getPageTitle(int position) {
    return fruitList[position];
}
    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dp_48"
        app:tabBackground="@color/white"
        app:tabGravity="center"
        app:tabIndicator="@drawable/center_tab_line"
        app:tabIndicatorFullWidth="false"
        app:tabIndicatorHeight="2dp"
        app:tabMode="scrollable"
        app:tabRippleColor="@null"
        app:tabSelectedTextColor="#1E90FF"
        tools:ignore="MissingConstraints">

主要是这个:

app:tabIndicator=“@drawable/center_tab_line”

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

    <item
        android:width="40dp"
        android:gravity="center_horizontal">
        <shape android:shape="rectangle">
            <solid android:color="#08A8F2" />
        </shape>
    </item>
</layer-list>

最后根据 android:width=“40dp” 就可以设置指定的宽度,我这里是40dp