TabLayout 中item设置宽度 API28以上

本文介绍了在API28及以上版本中,如何通过代码反射方式解决TabLayout item宽度设置无效的问题,特别强调了当只有一个item时可能存在的限制。
摘要由CSDN通过智能技术生成

首先说明一下,TabLayout 中如果只用一个item的时候,此时设置是不起作用,原因我也没查,估计是源码底层做了限制

 		<!--tabIndicatorColor 底下标签的颜色值-->
        <!--tabSelectedTextColor 选中时的文字的颜色-->
        <!--tabBackground 整个item的背景-->
        <!--tabTextColor 默认item文字的颜色-->
        <!--tabTextAppearance 指定 文字的大小-->
        <!-- 设置TabLayout 文字的大小-->
 <style name="TabLayoutTextStyle">
        <item name="android:textSize">14sp</item>
 </style>
 <com.google.android.material.tabs.TabLayout
            android:layout_width="match_parent"
            android:id="@+id/tabLayout"
            app:tabIndicatorColor="@color/text_press" //
            app:tabSelectedTextColor="@color/text_press"
            app:tabBackground="@color/mid_blue"
            app:tabTextColor="@color/white"
            app:tabTextAppearance=
可以通过自定义TabLayout的TabView来实现设置每个Tab的宽度。 1. 首先,创建一个自定义的TabView布局文件,例如tab_item.xml,设置TabView的宽度为固定值或者match_parent,例如: ```xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <TextView android:id="@+id/tab_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@drawable/tab_text_color_selector" android:textSize="14sp"/> </LinearLayout> ``` 2. 在代码设置TabLayout的自定义布局,例如: ```java TabLayout tabLayout = findViewById(R.id.tab_layout); tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE); for (int i = 0; i < tabLayout.getTabCount(); i++) { TabLayout.Tab tab = tabLayout.getTabAt(i); if (tab != null) { View tabView = LayoutInflater.from(this).inflate(R.layout.tab_item, null); TextView textView = tabView.findViewById(R.id.tab_text); textView.setText(tab.getText()); tab.setCustomView(tabView); } } // 设置每个Tab的宽度 for (int i = 0; i < tabLayout.getTabCount(); i++) { TabLayout.Tab tab = tabLayout.getTabAt(i); if (tab != null && tab.getCustomView() != null) { View tabView = tab.getCustomView(); tabView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); int width = tabView.getMeasuredWidth(); LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) tabView.getLayoutParams(); layoutParams.width = width; tabView.setLayoutParams(layoutParams); } } ``` 上面的代码,首先设置TabLayout的TabMode为MODE_SCROLLABLE,表示Tab可以滚动。然后,为每个Tab设置自定义布局,并设置每个Tab的宽度等于TabView的宽度。其,通过measure方法测量TabView的宽度,然后将宽度设置给TabView的LayoutParams即可。 需要注意的是,如果TabLayout的TabMode为MODE_FIXED,那么所有的Tab宽度都是相同的,无法设置不同的宽度
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值