I've followed Nick Butcher's Material Improvements I/O 2016 talk, and at about 6:00, he starts talking about animating list items. I've implemented the feature exactly as he was doing it, and the bound changes animate correctly, but color changes don't animate, despite him explicitly saying they would:
This is what the code looks like:
This is the relevant part of the RecyclerView.Adapter
class:
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val item: Pair<String, String> = items[position]
holder.title.text = item.first
holder.subtitle.text = item.second
val isExpanded = position == expandedPosition
holder.subtitle.visibility = if (isExpanded) View.VISIBLE else View.GONE
holder.itemView.isActivated = isExpanded
holder.itemView.setOnClickListener {
expandedPosition = if (isExpanded) -1 else position
TransitionManager.beginDelayedTransition(recyclerView)
notifyDataSetChanged()
}
}
This is the layout I'm using for the items. ConstraintLayout
is kind of overkill for the current layout setup, but I reduced the layout to create a minimal example.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".MainActivity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/item_background"
android:stateListAnimator="@animator/item_elevation"
android:padding="8dp">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
tools:text="Title 1"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
<TextView
android:id="@+id/subtitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:text="Subtitle 1"
app:layout_constraintTop_toBottomOf="@id/title"
app:layout_constraintStart_toStartOf="parent"
/>
</android.support.constraint.ConstraintLayout>
And this is the background I'm using for the item layout:
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:enterFadeDuration="@android:integer/config_mediumAnimTime"
android:exitFadeDuration="@android:integer/config_mediumAnimTime">
<item android:state_activated="true"
android:drawable="@color/colorAccent" />
<item android:drawable="@color/colorPrimaryDark" />
</selector>