Expandable views are a common way to hide details of a visualised data structures. Let’s take a look at how the following can be achieved in 6 steps, using compose:
Step 1: Creating a data class for card
@Immutable data class ExpandableCardModel(val id: Int, val title: String)
What does the Immutable annotation mean?
Quote from official documentation: “ The immutability of the class is not validated and is a promise by the type that all publicly accessible properties and fields will not change after the instance is constructed.
This is a stronger promise than val
as it promises that the value will never change not only that values cannot be changed through a setter.
Immutable is used by composition which enables composition optimisations that can be performed based on the assumption that values read from the type will not change.”
Step 2: Create a data source
We’ll be using AAC viewModel example here, but feel free to use any “controller” abstraction you like.
class CardsViewModel : ViewModel() { | |
private val _cards = MutableStateFlow(listOf<ExpandableCardModel>()) | |
val cards: StateFlow<List<ExpandableCardModel>> get() = _cards | |
private val _expandedCardIdsList = MutableStateFlow(listOf<Int>()) | |
val expandedCardIdsList: StateFlow<List<Int>> get() = _expandedCardIdsList | |
init { | |
getFakeData() | |
} | |
private fun getFakeData() { | |
viewModelScope.launch { | |
withContext(Dispatchers.Default) { | |
val testList = arrayListOf<ExpandableCardModel>() | |
repeat(20) { testList += ExpandableCardModel(id = it, title = "Card $it") } | |
_cards.emit(testList) | |
} | |
} | |
} | |
fun onCardArrowClicked(cardId: Int) { | |
_expandedCardIdsList.value = _expandedCardIdsList.value.toMutableList().also { list -> | |
if (list.contains(cardId)) list.remove(cardId) else list.add(cardId) | |
} | |
} | |
} |
CardsViewModel.kt
This class serves 4 purposes:
- Holds list of cards using MutableStateFlow in _cards field, and exposes a StateFlow to observers via cards field.
- Holds list of expanded card ids in _expandedCardIdsList, and exposes them to observers via expandedCardIdsList field.
- Provides list of cards using getFakeData() function. We need a coroutine here, to emit the testList into _cards.
- Contains a onCardArrowClicked() to mark cards as expanded by adding tapped card id to _expandedCardIdsList, and notify observers about this change by mutating the state of _expandedCardIdsList.
Step 3: MainActivity
class MainActivity : AppCompatActivity() { | |
private val cardsViewModel by viewModels<CardsViewModel>() | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContent { | |
AppTheme { | |
Surface(color = MaterialTheme.colors.background) { CardsScreen(cardsViewModel) } | |
} | |
} | |
} | |
} |
MainActivity.kt
We are initialising the CardsViewModel here, and providing it to the CardsScreen composable function.
Step 4: CardsScreen composable
@Composable | |
fun CardsScreen(viewModel: CardsViewModel) { | |
val cards by viewModel.cards.collectAsStateWithLifecycle() | |
val expandedCardIds by viewModel.expandedCardIdsList.collectAsStateWithLifecycle() | |
Scaffold { | |
LazyColumn { | |
items(cards, ExpandableCardModel::id) { card -> | |
ExpandableCard( | |
card = card, | |
onCardArrowClick = { viewModel.onCardArrowClicked(card.id) }, | |
expanded = expandedCardIds.contains(card.id), | |
) | |
} | |
} | |
} | |
} |
We are observing the viewModel.cards containing our list of cards, and viewModel.expandedCardIds with the help of .collectAsState().
What’s the purpose of .collectAsState()? It’s converting StateFlow into a State.
What’s a State? From the documentation: ” State is a value holder where reads to the value property during the execution of a composable function, the current recomposeScope will be subscribed to changes of that value.”
Step 5: ExpandableCard composable
@Composable | |
fun ExpandableCard( | |
card: ExpandableCardModel, | |
onCardArrowClick: () -> Unit, | |
expanded: Boolean, | |
) { | |
val transitionState = remember { | |
MutableTransitionState(expanded).apply { | |
targetState = !expanded | |
} | |
} | |
val transition = updateTransition(transitionState) | |
val cardBgColor by transition.animateColor({ | |
tween(durationMillis = EXPAND_ANIMATION_DURATION) | |
}) { | |
if (expanded) cardExpandedBackgroundColor else cardCollapsedBackgroundColor | |
} | |
val cardPaddingHorizontal by transition.animateDp({ | |
tween(durationMillis = EXPAND_ANIMATION_DURATION) | |
}) { | |
if (expanded) 48.dp else 24.dp | |
} | |
val cardElevation by transition.animateDp({ | |
tween(durationMillis = EXPAND_ANIMATION_DURATION) | |
}) { | |
if (expanded) 24.dp else 4.dp | |
} | |
val cardRoundedCorners by transition.animateDp({ | |
tween( | |
durationMillis = EXPAND_ANIMATION_DURATION, | |
easing = FastOutSlowInEasing | |
) | |
}) { | |
if (expanded) 0.dp else 16.dp | |
} | |
val arrowRotationDegree by transition.animateFloat({ | |
tween(durationMillis = EXPAND_ANIMATION_DURATION) | |
}) { | |
if (expanded) 0f else 180f | |
} | |
Card( | |
backgroundColor = cardBgColor, | |
contentColor = contentColour, | |
elevation = cardElevation, | |
shape = RoundedCornerShape(cardRoundedCorners), | |
modifier = Modifier | |
.fillMaxWidth() | |
.padding( | |
horizontal = cardPaddingHorizontal, | |
vertical = 8.dp | |
) | |
) { | |
Column { | |
Box { | |
CardArrow( | |
degrees = arrowRotationDegree, | |
onClick = onCardArrowClick | |
) | |
CardTitle(title = card.title) | |
} | |
ExpandableContent(visible = expanded, initialVisibility = expanded) | |
} | |
} | |
} |
ExpandableCard composable
val transitionState = remember { MutableTransitionState(expanded).apply { targetState = !expanded } }
Here we declare MutableTransitionState, and put it into our transition composable. Our initialState will depend on whether we have this card id in our expandedCardIds, and targetState will be a reversed initialState, since we only have 2 states.
Basically we have the following view hierarchy here:
Card (CardView) { Column (LinearLayout) { Box (FrameLayout) { CardArrow() (ImageView/Button) CardTitle() (TextView) } ExpandableContent()(views to expand/collapse) } }
Job Offers
Since we don’t suffer from multiple layout passes in compose ( except for ConstraintLayout as for now, but we won’t need it in most cases anyway with compose), we don’t need to worry about nesting layouts anymore.
Now let’s look how do we animate things, using previously defined transitionState on a Card example:
val cardBgColor by transition.animateColor({ | |
tween(durationMillis = EXPAND_ANIMATION_DURATION) | |
}) { | |
if (expanded) cardExpandedBackgroundColor else cardCollapsedBackgroundColor | |
} | |
val cardElevation by transition.animateDp({ | |
tween(durationMillis = EXPAND_ANIMATION_DURATION) | |
}) { | |
if (expanded) 24.dp else 4.dp | |
} |
animating background card colour & it’s elevation
This is where we define our start and end values for views ( elevation, colour, size, etc).
Card background colour will be white when card is collapsed and yellow when expanded. Elevation will be 24dp for an expanded card, and 4dp for a collapsed one.
Card( backgroundColor = cardBgColor, elevation = cardElevation, ...
Now we just pass these values to the composable, and that’s it.
Step 6: creating CardTitle, CardArrow and ExpandableContent composables
@Composable | |
fun CardTitle(title: String) { | |
Text( | |
text = title, | |
modifier = Modifier | |
.fillMaxWidth() | |
.padding(16.dp), | |
textAlign = TextAlign.Center, | |
) | |
} |
CardTitle composable
@Composable | |
fun CardArrow( | |
degrees: Float, | |
onClick: () -> Unit | |
) { | |
IconButton( | |
onClick = onClick, | |
content = { | |
Icon( | |
painter = painterResource(id = R.drawable.ic_expand_less_24), | |
contentDescription = "Expandable Arrow", | |
modifier = Modifier.rotate(degrees), | |
) | |
} | |
) | |
} |
CardArrow composable
Modifier.rotate(degrees)
allows us to rotate the arrow when we tap on it. arrowRotationDegree is being passed from ExpandableCard composable.
@Composable | |
fun ExpandableContent( | |
visible: Boolean = true, | |
initialVisibility: Boolean = false | |
) { | |
val enterTransition = remember { | |
expandVertically( | |
expandFrom = Alignment.Top, | |
animationSpec = tween(EXPANSTION_TRANSITION_DURATION) | |
) + fadeIn( | |
initialAlpha = 0.3f, | |
animationSpec = tween(EXPANSTION_TRANSITION_DURATION) | |
) | |
} | |
val exitTransition = remember { | |
shrinkVertically( | |
// Expand from the top. | |
shrinkTowards = Alignment.Top, | |
animationSpec = tween(EXPANSTION_TRANSITION_DURATION) | |
) + fadeOut( | |
// Fade in with the initial alpha of 0.3f. | |
animationSpec = tween(EXPANSTION_TRANSITION_DURATION) | |
) | |
} | |
AnimatedVisibility( | |
visible = visible, | |
initiallyVisible = initialVisibility, | |
enter = enterTransition, | |
exit = exitTransition | |
) { | |
Column(modifier = Modifier.padding(8.dp)) { | |
Spacer(modifier = Modifier.heightIn(100.dp)) | |
Text( | |
text = "Expandable content here", | |
textAlign = TextAlign.Center | |
) | |
} | |
} | |
} |
ExpandableContent composable
The most interesting part here is the AnimatedVisibility composable. It will do all the heavy lifting for us.
AnimatedVisibility attributes:
- visible, initiallyVisible – allow us to animate content only on first expansion. So when we scroll back to a card that was in expanded state before – no animation will be played
- enterFadeIn, enterExpand are EnterTransitions
- exitFadeOut, exitCollapse are ExitTransitions
That’s it, now you have an idea on how to create a basic expandable list with animations, using Jetpack Compose. If you have suggestions on how this example can be enhanced – please feel free to contact me.
Since compose is in alpha, and is destined to change — this post will be periodically updated to reflect the latest version. Post was created when compose was in 1.0.0-alpha09.
Current compose version 1.0.3.
Full, working example can be found here