前面呢,有寫過TabLayout的博客,最近開發用到了高本版遇到一些問題,來總結一下api
Android--------TabLayout實現新聞客戶端頂部導航欄post
Android中Tablayout設置下劃線寬度 和 dp和px之間進行相互轉換flex
上面是Api28版本以前是沒問題的 api28以後呢,有些地方就有所改變了spa
public static void reflex(final TabLayout tabLayout){ tabLayout.post(() -> { try { //拿到tabLayout的slidingTabIndicator屬性 Field tabIndicator = tabLayout.getClass().getDeclaredField("slidingTabIndicator"); //API28如下爲mTabStrip // Field tabIndicator = tabLayout.getClass().getDeclaredField("mTabStrip"); tabIndicator.setAccessible(true); LinearLayout mTabStrip = (LinearLayout) tabIndicator.get(tabLayout); int dp10 = dip2px(tabLayout.getContext(), 10); for (int i = 0; i < mTabStrip.getChildCount(); i++) { View tabView = mTabStrip.getChildAt(i); //拿到tabView的mTextView屬性 tab的字數不固定必定用反射取mTextView Field mTextViewField = tabView.getClass().getDeclaredField("textView"); //API28如下爲mTextView // Field mTextViewField = tabView.getClass().getDeclaredField("mTextView"); mTextViewField.setAccessible(true); TextView mTextView = (TextView) mTextViewField.get(tabView); tabView.setPadding(0, 0, 0, 0); //字多寬線就多寬,須要測量mTextView的寬度 int width = 0; width = mTextView.getWidth(); if (width == 0) { mTextView.measure(0, 0); width = mTextView.getMeasuredWidth(); } //設置tab左右間距爲10dp 這個間距可根據本身需求更改 LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams(); params.width = width ; params.leftMargin = dp10; params.rightMargin = dp10; tabView.setLayoutParams(params); tabView.invalidate(); } } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } }); }
固然這種方式啊我其實不是很推薦,我在網上也看到一些網友說設置了沒效果.net
因此我用了AndroidX 以後發現了他裏面的Tablayout 和以前有點的不太同樣了,並且也能實現了下劃線問題code
請看博客 blog