之前一直想用独立的compose控件来实现动画效果,感觉太麻烦了,最后还是用LazyColumn来实现,如果数据比较少,建议把数据的量增大到1000
代码如下
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun Banner1(viewModel: ScrollViewModel = androidx.lifecycle.viewmodel.compose.viewModel()) {
val scope = rememberCoroutineScope()
val list: MutableList<String> = mutableStateListOf()
repeat(500) {
list.add("item $it")
}
val state = rememberLazyListState()
val px = LocalDensity.current.run { 32.dp.toPx() }
var time by remember {
mutableStateOf(0L)
}
var stop = false
val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(Unit) {
val observer = LifecycleEventObserver { _, event ->
when (event) {
Lifecycle.Event.ON_PAUSE->{
stop = true
}
Lifecycle.Event.ON_RESUME -> {
stop = false
time = System.currentTimeMillis()
}
else -> {
}
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
}
}
LaunchedEffect(key1= time, key2 = stop) {
scope.launch {
delay(1000)
XLogger.d("--------->")
state.animateScrollBy(px)
if(!stop){
time = System.currentTimeMillis()
}
}
}
Box(modifier = Modifier.fillMaxSize()) {
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.height(((24 + 8) * 4).dp)
.pointerInteropFilter {
true
},
state = state,
content = {
items(count = list.size) { index ->
val data = list[index]
Box(
modifier = Modifier
.padding(start = 10.dp, end = 10.dp, top = 8.dp)
.fillMaxWidth()
.height(24.dp)
.background(
color = Color.Magenta,
shape = RoundedCornerShape(9.dp)
),
) {
Text(
data,
modifier = Modifier
.fillMaxWidth()
.padding(start = 10.dp),
fontSize = 12.sp,
color = Color.White
)
}
}
})
}
}