前面呢,有寫過TabLayout的博客,最近開發用到了高本版遇到一些問題,來總結一下
Android--------TabLayout實現新聞客戶端頂部導航欄
Android中Tablayout設置下劃線寬度 和 dp和px之間進行相互轉換
上面是Api28版本之前是沒問題的 api28之後呢,有些地方就有所改變了
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();
}
});
}
當然這種方式啊我其實不是很推薦,我在網上也看到一些網友說設置了沒效果
所以我用了AndroidX 之後發現了他裏面的Tablayout 和之前有點的不太一樣了,而且也能實現了下劃線問題
請看博客
AndroidX的 Tablayout(com.google.android.material.tabs.TabLayout) 的使用