Jetpack Compose - 一次性彩色动画

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

我需要在 Jetpack 中创建以下动画:

文本通常是灰色的,当发生某些事件(比如说消息到达)时,文本会变成绿色并慢慢淡出回到灰色。

我在“经典旧”XML 布局中使用 ObectAnimator 及其 .start() 方法做到了这一点:

val colorAnim = ObjectAnimator.ofInt(
                binding!!.tvLiveDataSource, "textColor",
                Color.argb(255, 173, 255, 0), Color.argb(255, 33, 49, 0)
            )
            colorAnim.duration = 5000
            colorAnim.setEvaluator(ArgbEvaluator())
            colorAnim.start()

但是我找不到任何可用的 Jetpack 示例。所有示例都在真/假变量之间切换,并基于它进行动画颜色过渡。它不适用于我的情况,因为我需要触发一次从绿色到灰色的转换。

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

您可以使用

animateColorAsState
更改
Text
的颜色。

预览

import androidx.compose.animation.animateColorAsState
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@Preview
@Composable
fun Stack025(modifier: Modifier = Modifier) {

    var animateBackgroundColor by remember {
        mutableStateOf(false)
    }

    val scope = rememberCoroutineScope()

    val animatedColor by animateColorAsState(
        targetValue = if (animateBackgroundColor) Color.Red else Color.Blue,
        label = "color"
    )

    Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Text(
            text = "Sample Text",
            color = animatedColor,
            modifier = Modifier.padding(12.dp)
        )

        Button(onClick = {
            scope.launch {
                animateBackgroundColor = true
                delay(800)
                animateBackgroundColor = false
            }
        }) {
            Text(text = "Click to receive msg")
        }

    }

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