jetpack compose - 惰性行中项目的动画输入比例

问题描述 投票:0回答:1

我正在尝试为

LazyRow
中的项目设置动画,这样当屏幕启动时,项目就会缩小。 我设法做到了这一点,但问题是,它不仅仅在屏幕启动时发生,而是在用户滚动项目时发生,并且它们以动画比例重新出现。

这是我的代码:

@Composable
fun ChooseUI(
    modifier: Modifier,
    navAction: () -> Unit,
    count: Int
) {
    
    ...
    
    LazyRow(
            modifier = modifier,
            contentPadding = PaddingValues(horizontal = 8.dp),
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            items(count = count,
                key = {
                    it
                }) {
                CustomControlCard(
                    controlId = it,
                    modifier = modifier,
                    navAction = {},
                    packageName = packageName,
                    resourceFolder = resourceFolder,
                )
            }
        }
    }
}

@SuppressLint("DiscouragedApi")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun CustomControlCard(
    modifier: Modifier,
    navAction: (String) -> Unit,
    controlId: Int,
    packageName: String,
    resourceFolder: Resources,
) {
    ...
    val scale = remember {
        Animatable(initialValue = 0f)
    }
    LaunchedEffect(true) {
        scale.animateTo(
            targetValue = 1f,
            animationSpec = tween(
                durationMillis = 250,
                delayMillis = 100*remoteId,
                easing = LinearEasing
            )
        )
    }

    Card(
        modifier = modifier
            .size(width = 110.dp, height = 200.dp)
            .scale(scale = scale.value),
        onClick = { }
    ) {
        Box(
            modifier = modifier
                .fillMaxWidth()
                .background(MaterialTheme.colorScheme.surface),
            contentAlignment = Alignment.BottomCenter,
        ) {
            Image(
                painter = painterResource(id = drawableId),
                contentDescription = null,
                alignment = Alignment.Center,
                modifier = Modifier
                    .padding(5.dp)
                    .fillMaxSize()
            )
        }
    }
}

正如我所说,它可以工作,而且当用户滚动列表时它也会显示动画,而不是在项目第一次出现时只显示一次。

知道如何解决这个问题吗?

android android-jetpack-compose android-animation
1个回答
0
投票

目前,每次 CustomControlCard 重新组合时(例如滚动时),动画都会运行。如果你想让它只运行一次,你可以设置动画的状态,如下所示:

val animated = remember { mutableStateOf(false) }
    
    if (!animated.value) {
        val scale = remember {
            Animatable(initialValue = 0f)
        }
        LaunchedEffect(true) {
            scale.animateTo(
                targetValue = 1f,
                animationSpec = tween(
                    durationMillis = 250,
                    delayMillis = 100 * remoteId,
                    easing = LinearEasing
                )
            )
            animated.value = true
        }
    }

这里,一旦运行,状态就会设置为true,因此不会再次运行。

© www.soinside.com 2019 - 2024. All rights reserved.