欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android TabLayout設(shè)置指示器寬度的方法

 更新時間:2018年04月03日 08:30:29   作者:夏天吃冰棍  
本篇文章主要介紹了Android TabLayout設(shè)置指示器寬度的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

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è)計要求,這么好的組件無法使用還需要自定義費時費力。這個時候我們可以通過反射機制拿到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();
  }
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論