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

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

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

anroid 5.0 Design  v7 包中引用了TabLayout 簡(jiǎn)單快速的寫(xiě)出屬于自己的Tab切換效果 如圖所示:

但是正常使用中你發(fā)現(xiàn)無(wú)法設(shè)置tablayout指示器的寬度。查看源碼你會(huì)發(fā)現(xiàn)設(shè)計(jì)師將指示器的寬度設(shè)置成TabView最大的寬度。并且設(shè)計(jì)師并沒(méi)有給我們暴漏出接口,這導(dǎo)致有時(shí)使用TabLayout無(wú)法滿(mǎn)足一些產(chǎn)品設(shè)計(jì)要求,這么好的組件無(wú)法使用還需要自定義費(fèi)時(shí)費(fèi)力。這個(gè)時(shí)候我們可以通過(guò)反射機(jī)制拿到TabLayout中的指示器對(duì)象對(duì)它的寬度進(jìn)行處理就可以滿(mǎn)足我們的要求:具體代碼如下

重寫(xiě)  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();
  }
}

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

相關(guān)文章

最新評(píng)論