Android Jetpack Compose中的跑马灯(Marquee)效果实现

Android Jetpack Compose中的跑马灯(Marquee)效果实现

blog logo

配置

marquee 修饰符可从依赖项1.4.0的版本中获得androidx.compose.foundation:foundation。如果您使用以下任一依赖项 —androidx.compose.material3:material3androidx.compose.material:material,那么您只需升级到1.4.0上述库即可。这是因为这两个material库都依赖于基础模块。因此,升级它们的版本也将隐式更新基础模块的版本。

dependencies {
    // if you're using material design 2
    implementation 'androidx.compose.material3:material:1.4.0'
    // if you're using material design 3
    implementation 'androidx.compose.material3:material3:1.4.0'
    // if you're just using foundation directly
    implementation 'androidx.compose.foundation:foundation:1.4.0'
}

或者,如果您正在使用Compose Bill Of Materials(BOM),则升级bom的版本到2023.03.00。

https://developer.android.com/jetpack/compose/bom/bom

dependencies {
    def composeBom = platform('androidx.compose:compose-bom:2023.03.00')
    implementation composeBom
    androidTestImplementation composeBom
}

将跑马灯效果应用于组合式非常简单。只需在您想要添加跑马灯效果的组合式上使用 basicMarquee() 修饰符即可。就是这么简单!在撰写本文时,basicMarquee() 修饰符带有 @ExperimentalFoundationApi 注释。因此,您可以使用 @OptIn(ExperimentalFoundationApi::class) 注释进行选择加入,或者在使用修饰符的组合式上使用 @ExperimentalFoundationApi 进行传播。以下是一个示例。

@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun MarqueeEffect() {
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Text(
            modifier = Modifier.basicMarquee(),
            text = "Compose has finally added support for Marquee! It's soo easy to implement!"
        )
    }
}

Marquee 修饰符被应用于文本组合式

marquee 修饰符应用于非文本组合

是的,您读对了!作为修饰符,marquee 修饰符也可以应用于任何组合式,而不仅仅是文本组合式。以下是在非文本组合式上使用它的示例。

@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun MarqueeEffect() {
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Row(modifier = Modifier.basicMarquee()) {
            repeat(30) {
                Box(
                    modifier = Modifier
                        .size(30.dp)
                        .background(Color.Red)
                )
                Spacer(modifier = Modifier.width(8.dp))
            }
        }
    }
}

Marquee 修饰符被应用于非文本组合式

basicMarquee() 修饰符的几点需要注意的事项

  • 只有当应用了该修饰符的组合式的内容过宽而无法适应可用空间时,修饰符才会应用跑马灯效果。如果内容能够适应可用空间,则修饰符无效。

  • 如果动画正在运行,则当传递给修饰符的任何参数发生更改或内容/容器组合式的大小发生更改时,它将重新启动。

  • 无限制地保持跑马灯动画运行并不是一个好主意,因为它可能会影响电池寿命,而且从用户体验的角度来看,这并没有什么意义。一个很好的默认值是仅在用户表明想要查看更多内容时才运行动画,例如通过单击内容。

将跑马灯效果应用于更实际的情况中

如前所述,长期运行跑马灯动画并不理想。一个改进的方式是仅在组合在焦点时运行动画。可以通过利用modifier的animationMode参数来实现这一点。

@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun MarqueeEffect() {
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        val focusRequester = remember { FocusRequester() }
        Text(
            modifier = Modifier
                .basicMarquee(animationMode = MarqueeAnimationMode.WhileFocused)
                .focusRequester(focusRequester)
                .focusable()
                .clickable { focusRequester.requestFocus() },
            text = "Compose has finally added support for Marquee! It's soo easy to implement!"
        )
    }
}

仅在有焦点状态下才运行跑马灯效果

结论

本篇博客介绍了basicMarquee()修饰符的使用方法,我们仅仅是对其进行了浅显的讲解,还有许多不同的参数可以对修饰符的行为进行自定义,大家一定要多加尝试和探索!

实现跑马灯效果,可以使用`Animatable`和`AnimatableVector`来创建一个自定义的跑马灯效果的`Text`控件。 首先,需要添加以下依赖到你的项目: ```kotlin implementation "androidx.compose.animation:animation:1.0.0" implementation "androidx.compose.animation:animation-core:1.0.0" implementation "androidx.compose.animation:animation-graphics:1.0.0" ``` 然后,可以创建一个自定义的`MarqueeText`控件,继承自`Text`: ```kotlin import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.* import androidx.compose.animation.core.AnimationConstants.Infinite import androidx.compose.foundation.layout.Box import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.vector.PathNode import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp @Composable fun MarqueeText( text: String, modifier: Modifier = Modifier, speed: Dp = 100.dp, textColor: Color = Color.Black, backgroundColor: Color = Color.White, ) { var textWidth by remember { mutableStateOf(0f) } var offsetX by remember { mutableStateOf(0f) } var isRunning by remember { mutableStateOf(false) } val infiniteTransition = rememberInfiniteTransition() val animatedValue = animateFloatAsState( targetValue = if (isRunning) -textWidth else 0f, animationSpec = infiniteRepeatable( animation = tween(durationMillis = (textWidth / speed).toInt(), easing = LinearEasing), repeatMode = RepeatMode.Restart, ) ) LaunchedEffect(text) { isRunning = true } Box(modifier = modifier) { Text( text = text, modifier = Modifier.alpha(0f), onTextLayout = { layoutResult -> textWidth = layoutResult.size.width.toFloat() } ) Box( modifier = Modifier.offset(x = animatedValue.value) .onSizeChanged { size -> offsetX = size.width.toFloat() } ) { Text( text = text, modifier = Modifier.offset(x = offsetX), color = textColor, onTextLayout = { layoutResult -> textWidth = layoutResult.size.width.toFloat() } ) } Box( modifier = Modifier.offset(x = animatedValue.value + offsetX) .onSizeChanged { size -> offsetX += size.width.toFloat() } ) { Text( text = text, color = textColor, backgroundColor = animateColorAsState(targetValue = backgroundColor).value, onTextLayout = { layoutResult -> textWidth = layoutResult.size.width.toFloat() } ) } } } ``` 然后,你可以在你的Compose函数使用`MarqueeText`控件来实现跑马灯效果: ```kotlin @Composable fun MyScreenContent() { MarqueeText( text = "Hello, Jetpack Compose!", modifier = Modifier.fillMaxWidth(), speed = 100.dp, textColor = Color.White, backgroundColor = Color.Blue, ) } ``` 这样,你就可以在你的界面上看到一个带有跑马灯效果的文本了。你可以根据需要调整`speed`来控制跑马灯的速度,`textColor`和`backgroundColor`来设置文本和背景颜色。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Calvin880828

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值