先上效果图:

 实现步骤:

1.创建tab后重新设置maskDrawable.setConrnerRadius的值

private TabLayout.Tab newTabView(TabLayout parent, String name) {
        
        TabLayout.Tab tab = parent.newTab().setText(name);
        TabLayout.TabView tabView = tab.view;
        ColorStateList tabRippleColorStateList = parent.getTabRippleColor();
        boolean unboundedRipple=parent.hasUnboundedRipple();

        Drawable background;
        Drawable contentDrawable = new GradientDrawable();
        ((GradientDrawable) contentDrawable).setColor(Color.TRANSPARENT);

        if (tabRippleColorStateList != null) {
            GradientDrawable maskDrawable = new GradientDrawable();
            maskDrawable.setCornerRadius(10F);//重点,参见Tablayout源码修改
            maskDrawable.setColor(Color.WHITE);

            ColorStateList rippleColor =
                    RippleUtils.convertToRippleDrawableColor(tabRippleColorStateList);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                background =
                        new RippleDrawable(
                                rippleColor,
                                unboundedRipple ? null : contentDrawable,
                                unboundedRipple ? null : maskDrawable);
            } else {
                Drawable rippleDrawable = DrawableCompat.wrap(maskDrawable);
                DrawableCompat.setTintList(rippleDrawable, rippleColor);
                background = new LayerDrawable(new Drawable[]{contentDrawable, rippleDrawable});
            }
        } else {
            background = contentDrawable;
        }
        ViewCompat.setBackground(tabView, background);
        parent.invalidate();
        return tab;
    }

2.XML

重点属性

  • app:tabUnboundedRipple 需要为false
  • android:background="@android:color/transparent"
  • app:tabRippleColor="@color/white"
<com.google.android.material.tabs.TabLayout
      android:id="@+id/tabtest"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_marginStart="72dp"
      android:layout_marginTop="12dp"
      app:tabIndicator="@drawable/tab_indicator"
      app:tabUnboundedRipple="false"
      app:tabRippleColor="@color/white"
      android:background="@android:color/transparent"
      app:tabGravity="center"
      app:tabIndicatorHeight="5dp"
      app:tabMinWidth="98dp"
      app:tabPaddingBottom="7dp"
      app:tabSelectedTextColor="@color/white"
      app:tabTextColor="#8E8E8E"
      app:tabIndicatorColor="#FF634EB7"/>

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐