首页 > 系统 > Android > 正文

Android TabLayout设置指示器宽度的方法

2019-10-22 18:13:16
字体:
来源:转载
供稿:网友

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

tablayout,指示器宽度,指示器

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

重写  onMeasure方法

@Overrideprotected 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();  }}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持VEVB武林网。


注:相关教程知识阅读请移步到Android开发频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表