Blog Infos
Author
Published
Topics
, ,
Published

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:

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:

  1. Holds list of cards using MutableStateFlow in _cards field, and exposes a StateFlow to observers via cards field.
  2. Holds list of expanded card ids in _expandedCardIdsList, and exposes them to observers via expandedCardIdsList field.
  3. Provides list of cards using getFakeData() function. We need a coroutine here, to emit the testList into _cards.
  4. 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) }
}
}
}
}
view raw MainActivity.kt hosted with ❤ by GitHub

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),
)
}
}
}
}
view raw CardsScreen.kt hosted with ❤ by GitHub

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

Job Offers


    Android Software Engineer (f/m/d)

    Paradox Cat GmbH
    Munich
    • Full Time
    apply now

    Android Test Automation Engineer

    Komoot
    Remote
    • Full Time
    apply now

    Senior Android Software Engineer (f/m/d)

    Paradox Cat GmbH
    Munich
    • Full Time
    apply now

OUR VIDEO RECOMMENDATION

,

Branching out to Jetpack Compose

As one of the most widely used social media platforms, Twitter is always hunting for ways to better connect its users. In early 2021 the Client UI team at Twitter began the task of integrating…
Watch Video

Branching out to Jetpack Compose

Nacho López & Chris Banes
Staff Software Engineer
Twitter

Branching out to Jetpack Compose

Nacho López & Chr ...
Staff Software Engin ...
Twitter

Branching out to Jetpack Compose

Nacho López & C ...
Staff Software Engineer
Twitter

Jobs

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,
)
}
view raw CardTitle.kt hosted with ❤ by GitHub

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),
)
}
)
}
view raw CardArrow.kt hosted with ❤ by GitHub

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:
  • visibleinitiallyVisible – 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
  • enterFadeInenterExpand are EnterTransitions
  • exitFadeOutexitCollapse 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

YOU MAY BE INTERESTED IN

YOU MAY BE INTERESTED IN

blog
It’s one of the common UX across apps to provide swipe to dismiss so…
READ MORE
blog
In this part of our series on introducing Jetpack Compose into an existing project,…
READ MORE
blog

How to animate BottomSheet content using Jetpack Compose

Early this year I started a new pet project for listening to random radio…
READ MORE
blog
Yes! You heard it right. We’ll try to understand the complete OTP (one time…
READ MORE

1 Comment. Leave new

  • SC
    11.09.2022 13:08

    Any way to make this work with nested list of expandable cards inside each expandable card?

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

Menu