Blog Infos
Author
Published
Topics
Published

Understanding the component

Code
data class Account(@DrawableRes val image: Int)

private val accounts = listOf(
    Account(image = R.drawable.goat),
    Account(image = R.drawable.horse),
    Account(image = R.drawable.monkey)
)

After that I created the AccountSwitcher component that receives a list of accounts, the current account and a callback that’s called when the account changes.

@Composable
fun AccountSwitcher(
    accounts: List<Account>,
    currentAccount: Account,
    onAccountChanged: (Account) -> Unit,
    modifier: Modifier = Modifier
) {
    ...
}

Inside AccountSwitcher I defined a few variables.

val imageSize = 36.dp
val imageSizePx = with(LocalDensity.current) { imageSize.toPx() }

val currentAccountIndex = accounts.indexOf(currentAccount)
var nextAccountIndex by remember { mutableStateOf<Int?>(null) }
var delta by remember(currentAccountIndex) { mutableStateOf(0f) }
val draggableState = rememberDraggableState(onDelta = { delta = it })
val targetAnimation = remember { Animatable(0f) }
LaunchedEffect(key1 = currentAccountIndex) {
    snapshotFlow { delta }
        .filter { nextAccountIndex == null }
        .filter { it.absoluteValue > 1f }
        .throttleFirst(300)
        .map { delta ->
            if (delta < 0) { // Scroll down (Bottom -> Top)
                if (currentAccountIndex < accounts.size - 1) 1 else 0
            } else { // Scroll up (Top -> Bottom)
                if (currentAccountIndex > 0) -1 else 0
            }
        }
        .filter { it != 0 }
        .collect { change ->
            nextAccountIndex = currentAccountIndex + change
            
            targetAnimation.animateTo(
                change.toFloat(),
                animationSpec = tween(easing = LinearEasing, durationMillis = 200)
            )

            onAccountChanged(accounts[nextAccountIndex!!])
            nextAccountIndex = null
            targetAnimation.snapTo(0f)
        }
}

OUR VIDEO RECOMMENDATION

, ,

Migrating to Jetpack Compose – an interop love story

Most of you are familiar with Jetpack Compose and its benefits. If you’re able to start anew and create a Compose-only app, you’re on the right track. But this talk might not be for you…
Watch Video

Migrating to Jetpack Compose - an interop love story

Simona Milanovic
Android DevRel Engineer for Jetpack Compose
Google

Migrating to Jetpack Compose - an interop love story

Simona Milanovic
Android DevRel Engin ...
Google

Migrating to Jetpack Compose - an interop love story

Simona Milanovic
Android DevRel Engineer f ...
Google

Jobs

No results found.

fun <T> Flow<T>.throttleFirst(periodMillis: Long): Flow<T> {
    require(periodMillis > 0) { "period should be positive" }
    return flow {
        var lastTime = 0L
        collect { value ->
            val currentTime = System.currentTimeMillis()
            if (currentTime - lastTime >= periodMillis) {
                lastTime = currentTime
                emit(value)
            }
        }
    }
}
Box(modifier = Modifier.size(imageSize)) {
        nextAccountIndex?.let { index ->
            Image(
                painter = painterResource(id = accounts[index].image),
                contentScale = ContentScale.Crop,
                contentDescription = "Account image",
                modifier = Modifier
                    .graphicsLayer {
                        scaleX = abs(targetAnimation.value)
                        scaleY = abs(targetAnimation.value)
                    }
                    .clip(CircleShape)
            )
        }
        
        Image(
            painter = painterResource(id = accounts[currentAccountIndex].image),
            contentScale = ContentScale.Crop,
            contentDescription = "Account image",
            modifier = Modifier
                .draggable(
                    state = draggableState,
                    orientation = Orientation.Vertical,
                )
                .graphicsLayer {
                    this.translationY = targetAnimation.value * imageSizePx * -1.5f
                }
                .clip(CircleShape)
        )
    }
var selectedAccount by remember { mutableStateOf(accounts[0]) }

AccountSwitcher(
    accounts = accounts,
    currentAccount = selectedAccount,
    onAccountChanged = { selectedAccount = it }
)

This article was previously published on proandroiddev.com

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
In the world of Jetpack Compose, where designing reusable and customizable UI components is…
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

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