Android TabLayout設(shè)置指示器寬度的方法
anroid 5.0 Design v7 包中引用了TabLayout 簡單快速的寫出屬于自己的Tab切換效果 如圖所示:

但是正常使用中你發(fā)現(xiàn)無法設(shè)置tablayout指示器的寬度。查看源碼你會發(fā)現(xiàn)設(shè)計師將指示器的寬度設(shè)置成TabView最大的寬度。并且設(shè)計師并沒有給我們暴漏出接口,這導(dǎo)致有時使用TabLayout無法滿足一些產(chǎn)品設(shè)計要求,這么好的組件無法使用還需要自定義費(fèi)時費(fèi)力。這個時候我們可以通過反射機(jī)制拿到TabLayout中的指示器對象對它的寬度進(jìn)行處理就可以滿足我們的要求:具體代碼如下
重寫 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();
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android開發(fā)中TextView文本過長滾動顯示實(shí)現(xiàn)方法分析
這篇文章主要介紹了Android開發(fā)中TextView文本過長滾動顯示實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了Android項目開發(fā)中TextView顯示超長文本的具體操作技巧與注意事項,需要的朋友可以參考下2018-02-02
Flutter定義tabbar底部導(dǎo)航路由跳轉(zhuǎn)的方法
這篇文章主要為大家詳細(xì)介紹了Flutter定義tabbar底部導(dǎo)航路由跳轉(zhuǎn)的方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-07-07
android從系統(tǒng)圖庫中取圖片的實(shí)例代碼
這篇文章主要介紹了android從系統(tǒng)圖庫中取圖片的方法,涉及Android讀取及選擇圖片等相關(guān)操作技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-07-07
Android開源AndroidSideMenu實(shí)現(xiàn)抽屜和側(cè)滑菜單
這篇文章主要為大家詳細(xì)介紹了Android開源AndroidSideMenu實(shí)現(xiàn)抽屜和側(cè)滑菜單,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-02-02
android app跳轉(zhuǎn)應(yīng)用商店實(shí)現(xiàn)步驟
這篇文章主要為大家介紹了android app跳轉(zhuǎn)應(yīng)用商店實(shí)現(xiàn)步驟詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11
Android編程中Perferences的用法實(shí)例分析
這篇文章主要介紹了Android編程中Perferences的用法,以實(shí)例形式較為詳細(xì)的分析了配置文件preferences.xml的功能、定義及使用方法,具有一定參考借鑒價值,需要的朋友可以參考下2015-11-11

