TabLayout 文字/图标/背景动画

介绍

在Tablayout的基础上添加字体或图标的缩放及颜色过渡动画等。

使用的Tablayout的版本:com.google.android.material:material:1.2.1

实现效果如下:

<img src="https://s1.ax1x.com/2020/10/04/08TUu8.gif" alt="效果图" style="zoom:50%;" />

实现功能:

1.修改Indicator动画

2.添加文字缩放及颜色过渡动画

3.添加自定义图标大小及缩放和颜色过渡动画

4.添加背景颜色过渡动画

说明:

文中所有代码块中的 //... 代表省略多行代码

准备:

从库中复制TabLayout、TabItem,TabLayoutMediator三个类到Tabs库并处理掉错误。

Tabs也是需要附加material库,这里主要是修改import和加@SuppressLint("RestrictedApi")注解

1.修改Indicator动画

分析下改Indicator动画的特点,在页面滑动的前一半Indicator 的宽度由短逐渐变长,滑动的后一半Indicator 的宽度再由长逐渐变短。

我们知道Indicator动画是由SlidingTabIndicator来完成的。首先分析下draw方法

@Override
    public void draw(@NonNull Canvas canvas) {
     //...
      // Draw the selection indicator on top of tab item backgrounds
      if (indicatorLeft >= 0 && indicatorRight > indicatorLeft) {
        Drawable selectedIndicator;
        //...
        selectedIndicator.setBounds(indicatorLeft, indicatorTop, indicatorRight, indicatorBottom);
        //...
        selectedIndicator.draw(canvas);
      }
    //...
    }

由此看出只要我们按需求修改indicatorLeft和indicatorRight两个成员变量的值就可以实现需要的效果了。

经过一番努力找到

1.当左右滑动时,onPageScrolled时会调用TabLayout的setScrollPosition方法

public void setScrollPosition(int position,
      float positionOffset,
      boolean updateSelectedText,
      boolean updateIndicatorPosition) {
    //...
    // Set the indicator position, if enabled
    if (updateIndicatorPosition) {
      slidingTabIndicator.setIndicatorPositionFromTabPosition(position, positionOffset);
    }
    //...
}

最终需要在updateIndicatorPosition方法中修改即可。修改如下

private void updateIndicatorPosition() { 
    //...
    //下面注释的是原本代码
    //left = (int) (selectionOffset * nextTitleLeft + (1.0f - selectionOffset) * left);
    //right = (int) (selectionOffset * nextTitleRight + (1.0f - selectionOffset) * right);
    if (selectionOffset >=0.5){
        left = (int) (left + (2*(selectionOffset - 0.5f)*(nextTitleLeft - left)));
        right = right+(nextTitleRight - right);
    }else{
        right = (int) (right + 2*selectionOffset*(nextTitleRight - right));
    }
    //...
}

2.当点TabItem切换时,onPageSelected时会调用TabLayout的selectTab方法

@Override
public void onPageSelected(final int position) {
  final TabLayout tabLayout = tabLayoutRef.get();
  //...
    tabLayout.selectTab(tabLayout.getTabAt(position), updateIndicator);
 //...
}

经animateToTab方法

private void animateToTab(int newPosition) {
    //...
     // Set the indicator position, if enabled
    // Now animate the indicator
    slidingTabIndicator.animateIndicatorToPosition(newPosition, tabIndicatorAnimationDuration);
    //...
}

最终在updateOrRecreateIndicatorAnimation中修改即可。修改如下

void updateOrRecreateIndicatorAnimation(boolean recreateAnimation, final int position, int duration) {
    //...
    ValueAnimator.AnimatorUpdateListener updateListener =
          new ValueAnimator.AnimatorUpdateListener() {
            @SuppressLint("RestrictedApi")
            @Override
            public void onAnimationUpdate(@NonNull ValueAnimator valueAnimator) {
              final float fraction = valueAnimator.getAnimatedFraction();
                //下面注释的是原本代码
//              setIndicatorPosition(
//                  AnimationUtils.lerp(animationStartLeft, finalTargetLeft, fraction),
//                  AnimationUtils.lerp(animationStartRight, finalTargetRight, fraction));
              if (finalTargetLeft - animationStartLeft > 0) {
                if (fraction >= 0.5f) {
                  float tempF = 2 * (fraction - 0.5f);
                  int tempL = animationStartLeft + Math.round(tempF * (finalTargetLeft - animationStartLeft));
                  int tempR = animationStartRight + Math.round((finalTargetRight - animationStartRight));
                  setIndicatorPosition(tempL, tempR);
                } else {
                  float tempF = 2 * fraction;
                  int tempL = animationStartLeft;
                  int tempR = animationStartRight + Math.round(tempF * (finalTargetRight - animationStartRight));
                  setIndicatorPosition(tempL, tempR);
                }
              }else{
                if (fraction >= 0.5f) {
                  float tempF = 2 * (fraction - 0.5f);
                  int tempL = animationStartLeft + Math.round((finalTargetLeft - animationStartLeft));
                  int tempR = animationStartRight + Math.round(tempF*(finalTargetRight - animationStartRight));
                  setIndicatorPosition(tempL, tempR);
                }else{
                  float tempF = 2 * fraction;
                  int tempL = animationStartLeft + Math.round(tempF * (finalTargetLeft - animationStartLeft));
                  int tempR = animationStartRight ;
                  setIndicatorPosition(tempL, tempR);
                }
              }
            }
          };
    //...
}

到这里Indicator动画就修改结束了。

2.添加文字缩放及颜色过渡动画

选中字体和将选中的字体大小及颜色过渡动画。首先在value.xml中添加

<declare-styleable name="TabLayout">
<!--        text选择时的文字大小 不设置 没有字体缩放动画-->
        <attr name="tabSelectedTextSize" format="dimension" />
<!--        text的默认文字大小 -->
        <attr name="tabTextSize" format="dimension" />
</declare-styleable>

字体颜色就使用已有的tabSelectedTextColor和tabTextColor。

由于显示的文字是TabView的子View,所以文字缩放及颜色的动画都需要在TabView中完成。

第一步:仿照Indicator动画,在TabView中

1.当左右滑动时 ,添加setPositionFromTabPosition方法

2.当点TabItem切换时,添加animateFromTabPosition方法

由于代码有点多,这里就不在上代码了。文末会附上源码地址

第二步:与Indicator相似分别在相应的位置调用第一步添加的方法。

在setScrollPosition方法中

public void setScrollPosition(
      int position,
      float positionOffset,
      boolean updateSelectedText,
      boolean updateIndicatorPosition) {
    //...
    // Set the indicator position, if enabled
    if (updateIndicatorPosition) {
      slidingTabIndicator.setIndicatorPositionFromTabPosition(position, positionOffset);
    }
    if (updateIndicatorPosition) {
      Tab selectedTempTab = getTabAt(position);
      if (selectedTempTab != null) {
        selectedTempTab.view.setPositionFromTabPosition(position, positionOffset);
        int nextIndex = position + 1;
        if (positionOffset == 0) {
          if (nextPositionOffset > 0.5) {
            nextIndex = position - 1;
          } else {
            nextIndex = position + 1;
          }

        }
        Tab nextTab = getTabAt(nextIndex);
        if (nextTab != null) {
          nextTab.view.setPositionFromTabPosition(nextIndex, 1f - positionOffset);
        }
        nextPositionOffset = positionOffset;
      }
    }
    //...
}

在animateToTab方法中

private void animateToTab(int newPosition) {
    //...
     // Set the indicator position, if enabled
    // Now animate the indicator
    slidingTabIndicator.animateIndicatorToPosition(newPosition, tabIndicatorAnimationDuration);
    
    if (newPosition != getSelectedTabPosition()){
      Tab toTab = getTabAt(newPosition);
      Tab fromTab = getTabAt(getSelectedTabPosition());
      if (toTab != null && fromTab != null){
        toTab.view.animateFromTabPosition(false,tabIndicatorAnimationDuration);
        fromTab.view.animateFromTabPosition(true,tabIndicatorAnimationDuration);
      }
    }
    //...
}

至此文字的缩放及颜色动画的大致流程就说完了。具体细节如给文字预留一些距离等请查看源码。

3.添加自定义图标大小及缩放和颜色过渡动画

由于图标的缩放和颜色过渡动画和文字的非常相似,这里就不再叙说。

首先呢,这里说的自定义图标大小是自定义默认的图标大小,即tab.setIcon中的Icon大小。

实现思路:在setIcon时给ImageView设置大小。如下

@NonNull
public Tab setIcon(@Nullable Drawable icon) {
  this.icon = icon;
  //...
  view.initIconView();
  return this;
}
void initIconView(){
  LinearLayout.LayoutParams lp = (LayoutParams) iconView.getLayoutParams();
  if (tabIconWidth != 0) {
    lp.width = tabIconWidth;
  }
  if (tabIconHeight != 0){
    lp.height = tabIconHeight;
  }
  iconView.setLayoutParams(lp);
}

4.添加背景颜色过渡动画

实现方式和文字颜色过渡是相似的,这里就不再重复。

需注意点:

1.原本TabView的背景是设置的是点击水波纹效果,设置背景过渡动画会去除水波纹效果,动画结束需要重新设置点击水波纹效果

2.TabView的背景遮挡Indicator动画。需要把SlidingTabIndicator的draw方法的super.draw放到第一句

@Override
public void draw(@NonNull Canvas canvas) {
  // Draw the tab item contents (icon and label) on top of the background + indicator layers
  super.draw(canvas);
    //...
}

至此本文已结束。

特奉上 源码

该Library应用于小说阅读器 Z阅读

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,036评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,046评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,411评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,622评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,661评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,521评论 1 304
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,288评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,200评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,644评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,837评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,953评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,673评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,281评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,889评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,011评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,119评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,901评论 2 355