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

标签 android android-animation android-tablayout material-components-android material-components

我想让选项卡的背景平滑地动画到所选位置(就像默认的 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>

enter image description here

此处,Tab 3 被选中。如果我选择 Tab 1,背景应该从 Tab 3 动画到 Tab 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>

我在这里附上示例动画。只看标签栏。

enter image description here

是否有可能用我所遵循的方法实现这种动画?如果没有,请建议我另一种方式。这两天我一直在研究这个。还是想不通。

提前致谢。

最佳答案

我们在我们的应用程序中使用 TabLayout 实现了相同的效果。

enter image description here

平滑动画的诀窍是使用 tabIndicator attirbute 而不是 tabBackground!

您可以通过以下方式定义可绘制形状(不是选择器)并将其分配给 TabLayout:

app:tabIndicator="@drawable/tab_layout_fg"

这将添加一个带有您想要实现的流畅动画的选项卡指示器。 如果您发现 tabIndicator 颜色没有反射(reflect)可绘制文件中定义的颜色,您可以使用 tabIndicatorColor 属性为 tabIndicator 着色。

注意:确保您使用的是最新的设计支持库 v28.0.0 或适用于 Android X 的 Material 组件库。

关于android - 使用选择器时选项卡之间的平滑动画 - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58084965/

相关文章:

android - 升级Android Studio 3.6或更高版本

Android 导航回到 Activity;不要重新加载父级

android - 动画淡入淡出

安卓。另一个 tablayout 的选项卡内的 tablayout

android - 如何检查 ScrollView 是否可滚动

android - 无法卸载/mnt/secure/staging

android - 如何为新设计支持库的 FloatingActionButton 制作动画

安卓动画: How to change animation speed during Runtime

android - 没有viewpager的自定义Tablayout隐藏了textview

android - TabLayoutMediator 不保留 TabItem 属性