使用选择器时,选项卡之间的动画平滑-Android

Pra*_*een 3 android android-animation android-tablayout material-components material-components-android

我想使选项卡的背景平滑地动画到所选位置(就像tabIndicator选项卡之间的默认动画一样)。

这是我的TabLayout样子

<android.support.design.widget.TabLayout
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tabLayout"
        app:tabBackground="@drawable/tab_selector"
        app:tabTextColor="@color/white"
        android:background="@drawable/tab_layout_bg"         
    app:tabTextAppearance="@android:style/TextAppearance.Widget.TabWidget"
        app:tabIndicator="@null"
        app:tabRippleColor="@null">

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/tab1"/>

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/tab2"/>

        <android.support.design.widget.TabItem
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/tab3"/>

    </android.support.design.widget.TabLayout>
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

在这里,Tab 3被选中。如果我选择Tab 1的背景应该从动画Tab 3Tab 1

我正在使用选择器更改选项卡的背景。

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_selected="true"
        android:drawable="@drawable/tab_layout_fg"/>
    <item
        android:drawable="@drawable/tab_layout_bg"/>
</selector>
Run Code Online (Sandbox Code Playgroud)

在这里,我将附加示例动画。仅查看选项卡栏。

在此处输入图片说明

我遵循的方法是否可以实现这种动画?如果没有,请建议我另一种方式。我已经从两天开始从事这项工作。仍然无法弄清楚。

提前致谢。

Gab*_*tti 12

检查@Maulik 答案。这就是你要找的。
只是为了整合答案,没有自定义形状(在您的示例中您正在使用它),您可以使用:

 <com.google.android.material.tabs.TabLayout
      app:tabIndicatorGravity="stretch"
      app:tabIndicatorColor="@color/...."
      ..>
Run Code Online (Sandbox Code Playgroud)

INDICATOR_GRAVITY_STRETCH允许你伸展在整个高度和宽度的标签选择指示符。通过这种方式,您可以仅使用app:tabIndicatorColor不带可绘制对象来设置所使用的选定颜色。
默认情况下提供动画。


Mau*_*ani 5

We've achieved the same effect in our app using TabLayout.

在此处输入图片说明

The trick for smooth animation is to use tabIndicator attirbute instead of tabBackground!

You can define a shape drawable (not selector) and assign it to TabLayout by:

app:tabIndicator="@drawable/tab_layout_fg"
Run Code Online (Sandbox Code Playgroud)

This will add a tab indicator with smooth animation that you want to achieve. If you find that tabIndicator color is not reflecting as defined in the drawable file, you can tint the tabIndicator using tabIndicatorColor attribute.

Note: Make sure you're using latest design support library v28.0.0 or material components library for Android X.

  • 结合你的答案和@Gabriele 的答案对我有用。非常感谢。 (2认同)