最近做项目用到ViewPager TabLayout, 在使用TabLayout时遇到遇到以下问题
1、导航栏 字体个数不一致时,字体个数多的条目字体变小
2、导航条的宽度设置
针对问题一 效果图如下
源码中可以查看 字体默认大小为16sp
mTabTextSize = ta.getDimensionPixelSize( android.support.v7.appcompat.R.styleable.TextAppearance_android_textSize, 0);当换行时 系统会减小文字大小
if (mIconView != null && mIconView.getVisibility() == VISIBLE) { // If the icon view is being displayed, we limit the text to 1 line maxLines = 1; } else if (mTextView != null && mTextView.getLineCount() > 1) { // Otherwise when we have text which wraps we reduce the text size textSize = mTabTextMultiLineSize; }解决方法设置
indicator.setTabMode(TabLayout.MODE_SCROLLABLE);
针对问题二,相信大部分程序员都会碰到。
UI要求我们指示器中文字宽度与导航条宽度一致,但是使用TabLayout导航条宽度总是比文字部分宽度长。
下面我将带大家从源码查看原因:
我们需要了解 两个内部类class SlidingTabStrip extends LinearLayout //导航class TabView extends LinearLayout //导航文字 Textview icon
//添加导航Tab
private void addTabView(Tab tab) { final TabView tabView = tab.mView; mTabStrip.addView(tabView, tab.getPosition(), createLayoutParamsForTabs()); }
SlidingTabStrip 类onMeasure方法中会先记录TabView 宽度的最大值,然后将最大值赋值给每个TabView//记录最大值for (int i = 0, z = count; i < z; i++) { View child = getChildAt(i); if (child.getVisibility() == VISIBLE) { largestTabWidth = Math.max(largestTabWidth, child.getMeasuredWidth()); } }//值赋值给每个TabViewfor (int i = 0; i < count; i++) { final LinearLayout.LayoutParams lp = (LayoutParams) getChildAt(i).getLayoutParams(); if (lp.width != largestTabWidth || lp.weight != 0) { lp.width = largestTabWidth; lp.weight = 0; remeasure = true; } }由此可见导航条的宽度和文字的宽度有关
TabView系统配置 PaddingLeft = 12dp PaddingRight=12dp 所以导致导航条与导航文字宽度不一样
我们将padding设置为0后给TabView设置margin就Ok了。
解决方案:
public static void setIndicatorWith(TabLayout tabLayout){ try { Field mTabStripField = tabLayout.getClass().getDeclaredField("mTabStrip"); mTabStripField.setAccessible(true); LinearLayout mTabStrip = (LinearLayout) mTabStripField.get(tabLayout); int count = mTabStrip.getChildCount(); for(int i = 0;i<count;i++){ View mTabView = mTabStrip.getChildAt(i);//获取TabView mTabView.setPadding(0,0,0,0); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); layoutParams.leftMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,20, Resources.getSystem().getDisplayMetrics()); layoutParams.rightMargin =(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,20, Resources.getSystem().getDisplayMetrics()); mTabView.setLayoutParams(layoutParams); mTabView.invalidate(); } } catch (Exception e) { e.printStackTrace(); } }
写的比较乱,请大家多多包涵。。。。。