动画时在 RecyclerView 内折叠 CardView

Collapsing CardView inside RecyclerView when animating

我想做什么

我有一个 CardView,底部有一个支持文本,默认情况下是 GONE。我想让卡片的这一部分仅在用户单击 "action arrow" 时可见,如下图所示:

我知道我可以通过简单地将 View 可见性设置为 VISIBLE 来实现这一点,但我还想为展开和折叠事件设置动画。

问题以及我目前尝试过的方法

为此,我在我的 CardView xml 上使用了 android:animateLayoutChanges="true" 属性,它在扩展时工作得很好。但是一旦我再次单击箭头折叠支持文本,下面的卡片就会与我在动画期间单击的卡片重叠。我怎样才能避免这种重叠?

编辑: 我知道可以做类似 solution on this question 的事情,但它似乎过于复杂,因为存在 android:animateLayoutChanges 选项。我想知道是否可以使用 XML 属性 来解决我的问题,以保持简单。

我的动画代码如下:

Java代码

protected void expandCard() {
    if (isExpanded) {
        ibt_show_more.animate().rotation(0).start();
        isExpanded = false;
        tv_support.setVisibility(View.GONE);
    }
    else {
        ibt_show_more.animate().rotation(180).start();
        isExpanded = true;
        tv_support.setVisibility(View.VISIBLE);
    }
}

XML代码

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/spacing_small"
    card_view:cardCornerRadius="2dp"
    android:id="@+id/os_list_item_cv">

    <RelativeLayout
        android:id="@+id/os_list_item_rl_root"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:animateLayoutChanges="true">

        <!-- Here goes the header, the image, the action buttons and so on -->
        <!-- Omitted on purpose -->
        <!-- ... -->

        <!-- This is the support TextView -->
        <TextView
            android:id="@+id/tv_support"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/os_list_item_rl_actions"
            android:text="@string/bacon_ipsum"
            android:paddingBottom="24dp"
            android:paddingEnd="16dp"
            android:paddingRight="16dp"
            android:paddingLeft="16dp"
            android:paddingStart="16dp"
            android:visibility="gone"/>

    </RelativeLayout>

</android.support.v7.widget.CardView>

GIF 完整性(折叠行为错误)

在更改可见性之前,添加这行代码:

TransitionManager.beginDelayedTransition(the rootView containing the cardView, new AutoTransition()); 

你应该得到一个流畅的动画。在此之前,还要从您的 xml 中删除 "animateLayoutChanges=true"。

至于为什么会这样,调用 TransitionManager.beginDelayedTransition() 会使 TransitionManger 捕获父 ViewGroup 中的当前值并在下一个动画帧中渲染动画。本例中传递的 Transition 是一个 AutoTransition,它负责父 ViewGroup 中的所有淡入淡出、移动和调整大小。

Transitions and TransitionManager

还要注意在适当的情况下使用支持库中的转换,或执行必要的 API 级别检查。