我想创建一个图标,它可以在无限循环中每秒钟切换两种颜色。
我可以创建一个递归函数,但这会阻塞我的主线程,我正在考虑创建一个自定义视图,并使用post延迟来改变颜色和更容易的解决方案
这里有几个使用协程流的解决方案,我认为这比使用postDelayed
简单一点(至少如果你熟悉协程的话)。
第一个辅助函数:
fun <T> Flow<T>.repeatForever(): Flow<T> = flow {
while(true) { emitAll(this@repeatForever) }
}
传统观点// in Activity.onCreate() or Fragment.onViewCreated():
flowOf(Color.RED, Color.BLUE)
.onEach { color ->
ViewCompat.setBackgroundTintList(
binding.button,
ColorStateList.valueOf(color)
)
delay(1000)
}
.repeatForever()
.launchIn(lifecycleScope) // in a fragment use viewLifecycleOwner.lifecycleScope
private val buttonColor by remember {
flowOf(Color.Red, Color.Blue)
.onEach { delay(1000) }
.repeatForever()
.collectAsState(Color.Blue)
}
Button(
//...
color = buttonColor
) //...