软件编程
位置:首页>> 软件编程>> Android编程>> Android TabLayout设置指示器宽度的方法

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

作者:夏天吃冰棍  发布时间:2023-03-27 02:53:05 

标签: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();
 }
}

来源:https://www.jianshu.com/p/9d33679c3f78

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com