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)
        }
}

Job Offers

Job Offers


    Developer Relations Engineer

    Embrace
    United States
    • Full Time
    apply now

    Flutter Developers and Architects

    Rebell App Studio by Codemate
    Helsinki, Oulu, Bangkok
    • Full Time
    apply now

    Android Team Lead

    Komoot
    Remote EMEA
    • Full Time
    apply now
Load more listings

OUR VIDEO RECOMMENDATION

,

Exploration of Touch & Input in Jetpack Compose

etpack Compose has a layered approach to user interaction handling, all the way from high-level onClick parameters to dealing directly with low-level touch input. In this talk we’ll cover all these levels, discussing composable parameters,…
Watch Video

Exploration of Touch & Input in Jetpack Compose

Jolanda Verhoef
Android Developer Relations Engineer
Google

Exploration of Touch & Input in Jetpack Compose

Jolanda Verhoef
Android Developer Re ...
Google

Exploration of Touch & Input in Jetpack Compose

Jolanda Verhoef
Android Developer Relatio ...
Google

Jobs

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

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

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