随着谷歌推广Jetpack Compsoe框架,我们项目也积极拥抱变化在新业务页面中使用Compsoe技术开发。开发过程成遇到底纹词组件网上没找到方案,于是就手撸了一个compose版本的底纹词组件,废话不多说代码如下:
@Composable
fun TextBanner(
modifier: Modifier = Modifier,
list: List<String> = arrayListOf(),
delayMillis: Long = 3000, // 等待3秒
onItemChange: (String) -> Unit = {}
) {
val scope = rememberCoroutineScope()
var currentIndex by remember { mutableIntStateOf(0) }
LaunchedEffect(key1 = list) {
scope.launch {
while (list.isNotEmpty()) {
delay(delayMillis)
currentIndex = (currentIndex + 1) % list.size // 更新索引,实现循环滚动
onItemChange(list[currentIndex])
}
}
}
if(list.isNotEmpty()){
AnimatedContent(
targetState = currentIndex,
modifier = modifier,
transitionSpec = {
(slideIntoContainer(AnimatedContentTransitionScope.SlideDirection.Up) togetherWith
slideOutOfContainer(AnimatedContentTransitionScope.SlideDirection.Up))
},
contentAlignment = Alignment.Center
) { index ->
Text(
text = list[index],
modifier = Modifier.wrapContentHeight(),
color = Color(0xFFA4A4A4),
fontSize = 14.sp
)
}
}
}
希望对你有用!
在上个版本基础上添加了生命周期关联,主要是切出页面后要暂停循环,切回页面后继续文本循环,代码如下:
@Composable
fun TextBanner(
modifier: Modifier = Modifier,
list: List<String> = arrayListOf(),
delayMillis: Long = 3000, // 等待3秒
onItemChange: (String) -> Unit = {}
) {
val scope = rememberCoroutineScope()
var currentIndex by remember { mutableIntStateOf(0) }
var isLooping by remember { mutableStateOf(false) }
// 监听生命周期
val lifecycle = LocalLifecycleOwner.current.lifecycle
DisposableEffect(lifecycle) {
val lifecycleObserver = LifecycleEventObserver { _, event ->
when (event) {
Lifecycle.Event.ON_RESUME -> {
isLooping = true
}
Lifecycle.Event.ON_STOP -> {
isLooping = false
}
else -> {}
}
}
lifecycle.addObserver(lifecycleObserver)
onDispose {
lifecycle.removeObserver(lifecycleObserver)
}
}
LaunchedEffect(key1 = isLooping) {
scope.launch {
while (isLooping && list.isNotEmpty()) {
delay(delayMillis)
currentIndex = (currentIndex + 1) % list.size // 更新索引,实现循环滚动
onItemChange(list[currentIndex])
}
}
}
if(list.isNotEmpty()){
AnimatedContent(
targetState = currentIndex,
modifier = modifier,
transitionSpec = {
(slideIntoContainer(AnimatedContentTransitionScope.SlideDirection.Up) togetherWith
slideOutOfContainer(AnimatedContentTransitionScope.SlideDirection.Up))
},
contentAlignment = Alignment.Center, label = ""
) { index ->
Text(
text = list[index],
modifier = Modifier.wrapContentHeight(),
color = Color(0xFFA4A4A4),
fontSize = 14.sp
)
}
}
}