关于Android改变TabLayout 下划线(Indicator)宽度实践总结

本文介绍了如何在Android中改变TabLayout的Indicator宽度,包括通过反射设置和使用自定义View的方法。详细讲解了自定义View的实现过程,包括布局、状态处理和封装通用组件。并提到了第三方库MagicIndicator作为替代方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
});

}

效果图如下:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

提醒:这种方式改变Indicator最短也就Tab内容的宽度,如果设置很短,Tab内容就显示不下,如下图:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

二、通过TabLayout setCustomView 的方式

第一种通过反射的方式设置Indicator宽度,最短只能Tab内容的宽度,如果设计师要所有选中的Tab下的Indicator都设置一个指定的宽度,这种就不行了。TabLayout可以设置自定义View,可以通过这种方法来达到目的。

1, 将TabLayout 的tabIndicatorHeight 设置为0
2,通过TabLayout 的setCustomView方式添加Tab
3, 在onTabSelected 回调种,处理Tab选中和未选中的状态;
4,为了方便使用,封装成一个通用的View

首先看布局: enhance_tab_layout.xml:

<?xml version="1.0" encoding="utf-8"?>

<android.support.design.widget.TabLayout
android:id=“@+id/enhance_tab_view”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
app:tabIndicatorHeight=“0dp”

</android.support.design.widget.TabLayout>

Tab item 布局:tab_item_layout.xml

<?xml version="1.0" encoding="utf-8"?>



如上,TextView显示Tab内容,下面的View就是Tab下面的Indicator(下划线)。 自己定义的View,宽度随便你改。

添加Tab的时候使用setCustomView 方法:

/**

  • 添加tab
  • @param tab
    */
    public void addTab(String tab){
    mTabList.add(tab);
    View customView = getTabView(getContext(),tab,mIndicatorWidth,mIndicatorHeight,mTabTextSize);
    mCustomViewList.add(customView);
    mTabLayout.addTab(mTabLayout.newTab().setCustomView(customView));
    }

/**

  • 获取Tab 显示的内容
  • @param context
  • @param
  • @return
    */
    public static View getTabView(Context context,String text,int indicatorWidth,int indicatorHeight,int textSize) {
    View view = LayoutInflater.from(context).inflate(R.layout.tab_item_layout, null);
    TextView tabText = (TextView) view.findViewById(R.id.tab_item_text);
    if(indicatorWidth>0){
    View indicator = view.findViewById(R.id.tab_item_indicator);
    ViewGroup.LayoutParams layoutParams = indicator.getLayoutParams();
    layoutParams.width = indicatorWidth;
    layoutParams.height = indicatorHeight;
    indicator.setLayoutParams(layoutParams);
    }
    tabText.setTextSize(textSize);
    tabText.setText(text);
    return view;
    }

然后在onTabSelected中处理状态:

@Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
EnhanceTabLayout mTabLayout = mTabLayoutRef.get();
if(mTabLayoutRef!=null){
List customViewList = mTabLayout.getCustomViewList();
if(customViewList == null || customViewList.size() ==0){
return;
}
for (int i=0;i<customViewList.size();i++){
View view = customViewList.get(i);
if(view == null){
return;
}
TextView text = (TextView) view.findViewById(R.id.tab_item_text);
View indicator = view.findViewById(R.id.tab_item_indicator);
if(i == tab.getPosition()){ // 选中状态
text.setTextColor(mTabLayout.mSelectTextColor);
indicator.setBackgroundColor(mTabLayout.mSelectIndicatorColor);
indicator.setVisibility(View.VISIBLE);
}else{// 未选中状态
text.setTextColor(mTabLayout.mUnSelectTextColor);
indicator.setVisibility(View.INVISIBLE);
}
}
}

}

代码其实挺简单的,但是如果项目中多处使用到,都这样来处理的话,就显得麻烦,因此,我们通过自定义View的方式将这些代码疯转成1个通用的TabLayoutView。如下:

EnhanceTabLayout.java

/**

  • 对 support Design 包中的TabLayout包装
  • 主要实现功能:更改indicator 的长度
  • Created by zhouwei on 2018/5/18.
    */

public class EnhanceTabLayout extends FrameLayout {
private TabLayout mTabLayout;
private List mTabList;
private List mCustomViewList;
private int mSelectIndicatorColor;
private int mSelectTextColor;
private int mUnSelectTextColor;
private int mIndicatorHeight;
private int mIndicatorWidth;
private int mTabMode;
private int mTabTextSize;

public EnhanceTabLayout(@NonNull Context context) {
super(context);
init(context,null);
}

public EnhanceTabLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context,attrs);
}

public EnhanceTabLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context,attrs);
}

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public EnhanceTabLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context,attrs);
}

private void readAttr(Context context,AttributeSet attrs){
TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.EnhanceTabLayout);
mSelectIndicatorColor = typedArray.getColor(R.styleable.EnhanceTabLayout_tabIndicatorColor,context.getResources().getColor(R.color.colorAccent));
mUnSelectTextColor = typedArray.getColor(R.styleable.EnhanceTabLayout_tabTextColor, Color.parseColor(“#666666”));
mSelectTextColor = typedArray.getColor(R.styleable.EnhanceTabLayout_tabSelectTextColor,context.getResources().getColor(R.color.colorAccent));
mIndicatorHeight = typedArray.getDimensionPixelSize(R.styleable.EnhanceTabLayout_tabIndicatorHeight,1);
mIndicatorWidth = typedArray.getDimensionPixelSize(R.styleable.EnhanceTabLayout_tabIndicatorWidth,0);
mTabTextSize = typedArray.getDimensionPixelSize(R.styleable.EnhanceTabLayout_tabTextSize,13);
mTabMode = typedArray.getInt(R.styleable.EnhanceTabLayout_tab_Mode,2);
typedArray.recycle();
}

private void init(Context context,AttributeSet attrs){
readAttr(context,attrs);

mTabList = new ArrayList<>();
mCustomViewList = new ArrayList<>();
View view = LayoutInflater.from(getContext()).inflate(R.layout.enhance_tab_layout,this,true);
mTabLayout = view.findViewById(R.id.enhance_tab_view);

// 添加属性
mTabLayout.setTabMode(mTabMode == 1 ? TabLayout.MODE_FIXED:TabLayout.MODE_SCROLLABLE);
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
// onTabItemSelected(tab.getPosition());
// Tab 选中之后,改变各个Tab的状态
for (int i=0;i<mTabLayout.getTabCount();i++){
View view = mTabLayout.getTabAt(i).getCustomView();
if(view == null){
return;
}
TextView text = (TextView) view.findViewById(R.id.tab_item_text);
View indicator = view.findViewById(R.id.tab_item_indicator);
if(i == tab.getPosition()){ // 选中状态
text.setTextColor(mSelectTextColor);
indicator.setBackgroundColor(mSelectIndicatorColor);
indicator.setVisibility(View.VISIBLE);
}else{// 未选中状态
text.setTextColor(mUnSelectTextColor);
indicator.setVisibility(View.INVISIBLE);
}
}

}

@Override
public void onTabUnselected(TabLayout.Tab tab) {

}

@Override
public void onTabReselected(TabLayout.Tab tab) {

}
});
}

public List getCustomViewList(){
return mCustomViewList;
}

public void addOnTabSelectedListener (TabLayout.OnTabSelectedListener onTabSelectedListener){
mTabLayout.addOnTabSelectedListener(onTabSelectedListener);
}

/**

  • 与TabLayout 联动
  • @param viewPager
    */
    public void setupWithViewPager(@Nullable ViewPager viewPager) {
    mTabLayout.addOnTabSelectedListener(new ViewPagerOnTabSelectedListener(viewPager,this));
    }

/**

  • retrive TabLayout Instance
  • @return
    */
    public TabLayout getTabLayout(){
    return mTabLayout;
    }

/**

  • 添加tab
  • @param tab
    */
    public void addTab(String tab){
    mTabList.add(tab);
    View customView = getTabView(getContext(),tab,mIndicatorWidth,mIndicatorHeight,mTabTextSize);
    mCustomViewList.add(customView);
    mTabLayout.addTab(mTabLayout.newTab().setCustomView(customView));
    }

public static class ViewPagerOnTabSelectedListener implements TabLayout.OnTabSelectedListener{

private final ViewPager mViewPager;
private final WeakReference mTabLayoutRef;

public ViewPagerOnTabSelectedListener(ViewPager viewPager,EnhanceTabLayout enhanceTabLayout) {
mViewPager = viewPager;
mTabLayoutRef = new WeakReference(enhanceTabLayout);
}

@Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
EnhanceTabLayout mTabLayout = mTabLayoutRef.get();
if(mTabLayoutRef!=null){
List customViewList = mTabLayout.getCustomViewList();
if(customViewList == null || customViewList.size() ==0){
return;
}
for (int i=0;i<customViewList.size();i++){
View view = customViewList.get(i);
if(view == null){
return;
}
TextView text = (TextView) view.findViewById(R.id.tab_item_text);
View indicator = view.findViewById(R.id.tab_item_indicator);
if(i == tab.getPosition()){ // 选中状态
text.setTextColor(mTabLayout.mSelectTextColor);
indicator.setBackgroundColor(mTabLayout.mSelectIndicatorColor);
indicator.setVisibility(View.VISIBLE);
}else{// 未选中状态
text.setTextColor(mTabLayout.mUnSelectTextColor);
indicator.setVisibility(View.INVISIBLE);
}
}
}

}

@Override
public void onTabUnselected(TabLayout.Tab tab) {
// No-op
}

@Override
public void onTabReselected(TabLayout.Tab tab) {
// No-op
}
}

/**

  • 获取Tab 显示的内容
  • @param context
  • @param
  • @return
    */
    public static View getTabView(Context context,String text,int indicatorWidth,int indicatorHeight,int textSize) {
    View view = LayoutInflater.from(context).inflate(R.layout.tab_item_layout, null);
    TextView tabText = (TextView) view.findViewById(R.id.tab_item_text);
    if(indicatorWidth>0){
    View indicator = view.findViewById(R.id.tab_item_indicator);
    ViewGroup.LayoutParams layoutParams = indicator.getLayoutParams();
    layoutParams.width = indicatorWidth;
    layoutParams.height = indicatorHeight;
    indicator.setLayoutParams(layoutParams);
    }
    tabText.setTextSize(textSize);
    tabText.setText(text);
    return view;
    }

暴露了一些常用方法和原生TabLayout 的几个重要属性,自定义属性如下:

<?xml version="1.0" encoding="utf-8"?>

好了,这样就封装了一个可以改变Indicator 宽度的TabLayout,看一下怎么用,xml布局如下:

<com.example.codoon.customtablayout.EnhanceTabLayout
android:id=“@+id/enhance_tab_layout”
android:layout_marginTop=“30dp”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
app:tabIndicatorHeight=“2dp”
app:tabIndicatorWidth=“30dp”
app:tabTextColor=“#999999”
app:tab_Mode=“mode_scrollable”
app:tabSelectTextColor=“@color/colorPrimary”
app:tabIndicatorColor=“@color/colorPrimary”
app:tabTextSize=“6sp”

</com.example.codoon.customtablayout.EnhanceTabLayout>

Activity中代码如下:

mEnhanceTabLayout = findViewById(R.id.enhance_tab_layout);
mEnhanceTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
Log.e(“log”,“onTabSelected”);
}

@Override
public void onTabUnselected(TabLayout.Tab tab) {

}

@Override
public void onTabReselected(TabLayout.Tab tab) {

}
});
for(int i=0;i<sTitle.length;i++){
mEnhanceTabLayout.addTab(sTitle[i]);
}
mEnhanceTabLayout.setupWithViewPager(mViewPager);
List fragments = new ArrayList<>();
for(int i=0;i<sTitle.length;i++){
fragments.add(ItemFragment.newInstance(sTitle[i]));
}

MyAdapter adapter = new MyAdapter(getSupportFragmentManager(),fragments, Arrays.asList(sTitle));
mViewPager.setAdapter(adapter);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mEnhanceTabLayout.getTabLayout()));
mEnhanceTabLayout.setupWithViewPager(mViewPager);

注意,如果是配合ViewPager使用,需要下面两行代码,单独使用则不需要:

mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mEnhanceTabLayout.getTabLayout()));
mEnhanceTabLayout.setupWithViewPager(mViewPager);

最后看一下效果:(图中第二个TabLayout)

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

三、第三方开源库

如果前面2中方式都满足不了你的需求的话,你可以使用第三方库,也有一些不错的开源库,这里推荐2个。 **1 , MagicIndicator **

github:https://github.com/hackware1993/MagicIndicator star:4.4k

MagicIndicator ,使用方便,还有多种模式可以选择。包括:

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

有兴趣的可以去试一下。

repositories {

maven {
url “https://jitpack.io”
}
}

dependencies {

compile ‘com.github.hackware1993:MagicIndicator:1.5.0’
}

布局文件:

<net.lucode.hackware.magicindicator.MagicIndicator
android:id=“@+id/magic_indicator”
android:layout_width=“match_parent”
android:layout_height=“49dp”>

</net.lucode.hackware.magicindicator.MagicIndicator>

代码中:

MagicIndicator magicIndicator = (MagicIndicator) findViewById(R.id.magic_indicator);
CommonNavigator commonNavigator = new CommonNavigator(this);
commonNavigator.setAdapter(new CommonNavigatorAdapter() {

@Override
public int getCount() {
return sTitle == null ? 0 : sTitle.length;
}

@Override
public IPagerTitleView getTitleView(Context context, final int index) {
ColorTransitionPagerTitleView colorTransitionPagerTitleView = new ColorTransitionPagerTitleView(context);
colorTransitionPagerTitleView.setNormalColor(Color.GRAY);
colorTransitionPagerTitleView.setSelectedColor(Color.BLACK);
colorTransitionPagerTitleView.setText(sTitle[index]);
colorTransitionPagerTitleView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mViewPager.setCurrentItem(index);
}
});
return colorTransitionPagerTitleView;
}

@Override
public IPagerIndicator getIndicator(Context context) {
自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则近万的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

img

img

img

img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

如果你觉得这些内容对你有帮助,可以扫码获取!!(备注:Android)

题外话

我在一线互联网企业工作十余年里,指导过不少同行后辈。帮助很多人得到了学习和成长。

我意识到有很多经验和知识值得分享给大家,也可以通过我们的能力和经验解答大家在IT学习中的很多困惑,所以在工作繁忙的情况下还是坚持各种整理和分享。但苦于知识传播途径有限,很多程序员朋友无法获得正确的资料得到学习提升,故此将并将重要的Android进阶资料包括自定义view、性能优化、MVC与MVP与MVVM三大框架的区别、NDK技术、阿里面试题精编汇总、常见源码分析等学习资料。

【Android思维脑图(技能树)】

知识不体系?这里还有整理出来的Android进阶学习的思维脑图,给大家参考一个方向。

希望我能够用我的力量帮助更多迷茫、困惑的朋友们,帮助大家在IT道路上学习和发展~

《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!

13/H4lCoPEF.jpg" />

题外话

我在一线互联网企业工作十余年里,指导过不少同行后辈。帮助很多人得到了学习和成长。

我意识到有很多经验和知识值得分享给大家,也可以通过我们的能力和经验解答大家在IT学习中的很多困惑,所以在工作繁忙的情况下还是坚持各种整理和分享。但苦于知识传播途径有限,很多程序员朋友无法获得正确的资料得到学习提升,故此将并将重要的Android进阶资料包括自定义view、性能优化、MVC与MVP与MVVM三大框架的区别、NDK技术、阿里面试题精编汇总、常见源码分析等学习资料。

【Android思维脑图(技能树)】

知识不体系?这里还有整理出来的Android进阶学习的思维脑图,给大家参考一个方向。

[外链图片转存中…(img-DPoXAjs8-1713518237435)]

希望我能够用我的力量帮助更多迷茫、困惑的朋友们,帮助大家在IT道路上学习和发展~

《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值