温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android中TabLayout如何设置指示器宽度

发布时间:2021-06-17 14:06:05 来源:亿速云 阅读:123 作者:小新 栏目:移动开发

这篇文章主要介绍了Android中TabLayout如何设置指示器宽度,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

anroid 5.0 Design  v7 包中引用了TabLayout 简单快速的写出属于自己的Tab切换效果 如图所示:

Android中TabLayout如何设置指示器宽度

但是正常使用中你发现无法设置tablayout指示器的宽度。查看源码你会发现设计师将指示器的宽度设置成TabView最大的宽度。并且设计师并没有给我们暴漏出接口,这导致有时使用TabLayout无法满足一些产品设计要求,这么好的组件无法使用还需要自定义费时费力。这个时候我们可以通过反射机制拿到TabLayout中的指示器对象对它的宽度进行处理就可以满足我们的要求:具体代码如下

重写  onMeasure方法

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  int dp10 = CommUitls.dip2px(context, 10);
  LinearLayout mTabStrip = (LinearLayout) this.getChildAt(0);
  try {
    Field mTabs = TabLayout.class.getDeclaredField("mTabs");
    mTabs.setAccessible(true);
    ArrayList<Tab> tabs = (ArrayList<Tab>) mTabs.get(this);
    for (int i = 0; i < mTabStrip.getChildCount(); i++) {
      Tab tab = tabs.get(i);
      Field mView = tab.getClass().getDeclaredField("mView");
      mView.setAccessible(true);
      Object tabView = mView.get(tab);
      Field mTextView = context.getClassLoader().loadClass("android.support.design.widget.TabLayout$TabView").getDeclaredField("mTextView");
      mTextView.setAccessible(true);
      TextView textView = (TextView) mTextView.get(tabView);
      float textWidth = textView.getPaint().measureText(textView.getText().toString());
      View child = mTabStrip.getChildAt(i);
      child.setPadding(0, 0, 0, 0);
      LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((int) textWidth, LinearLayout.LayoutParams.MATCH_PARENT);
      params.leftMargin = dp10;
      params.rightMargin = dp10;
      child.setLayoutParams(params);
      child.invalidate();
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
}

感谢你能够认真阅读完这篇文章,希望小编分享的“Android中TabLayout如何设置指示器宽度”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI