Android中TabLayout怎么设置指示器宽度

本文小编为大家详细介绍“Android中TabLayout怎么设置指示器宽度”,内容详细,步骤清晰,细节处理妥当,希望这篇“Android中TabLayout怎么设置指示器宽度”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

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

Android中TabLayout怎么设置指示器宽度  android 免费ssr节点分享 第1张

但是正常使用中你发现无法设置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怎么设置指示器宽度”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注蜗牛博客行业资讯频道。

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

评论

有免费节点资源,我们会通知你!加入纸飞机订阅群

×
天气预报查看日历分享网页手机扫码留言评论电报频道链接