我有一個 LazyColumn,它有多個串列,它應該根據index值顯示。但是,當我更改index串列時,串列會更改,但是直到我向下滾動并向上滾動時,專案才會重新繪制。我已經把remember關鍵字扔了,改變了N次邏輯,但它仍然不會更新。這是我的課
@Composable
fun MainContent() {
val state = homeViewModel.state.collectAsState(initial = HomepageState.Loading)
Theme(config = config) {
when (state.value) {
is HomepageState.Loading -> Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) { CircularProgressIndicator() }
is HomepageState.Multi -> with(state.value as HomepageState.Multi) {
updateHomepageImagePreference(index)
LazyColumnContent(homepage = items, switcher, logo, index)
}
}
}
}
homepage[index] 部分是我想觸發重組的部分。我試圖傳遞正確的串列而不是更改索引,但結果是一樣的
@Composable
private fun LazyColumnContent(
homepage: List<List<ModuleConfig>>,
switcher: HomepageSwitcherTheme?,
logo: HomepageThemeNavLogo?,
index: Int = 0
) {
LaunchedEffect(key1 = index) {
updateHomepageSwitcher(switcher)
updateNavigationBarLogo(logo)
}
return LazyColumn(
modifier = Modifier
.fillMaxSize()
.background(vennConfig.themeConfig.backgroundColor?.color)
) {
itemsIndexed(homepage[index]) { _, item ->
AndroidView(
modifier = Modifier.fillMaxSize(),
factory = {
val productsInCategoryCriteriaSatisfied =
if (item.requiresProductsInCategoryId.isNullOrEmpty()) true
else categoryHasProducts[item.requiresProductsInCategoryId] ?: true
return@AndroidView if (productsInCategoryCriteriaSatisfied) moduleFactory.build(
item,
requireContext()
)
else View(context) // blank view
}
)
}
}
}
我猜我的 Compose 用法有問題,但我不知道是什么。
uj5u.com熱心網友回復:
AndroidView factory僅在視圖出現后才被呼叫。如果需要item在同一視圖上更新,可以使用update. 此外,當您沒有可顯示的內容時,您無需創建空視圖,只需AndroidView按需創建:
val productsInCategoryCriteriaSatisfied =
if (item.requiresProductsInCategoryId.isNullOrEmpty()) true
else categoryHasProducts[item.requiresProductsInCategoryId] ?: true
if (productsInCategoryCriteriaSatisfied) {
AndroidView(
modifier = Modifier.fillMaxSize(),
factory = { context ->
moduleFactory.build(
item,
context
)
},
update = {
it.item = item
},
)
}
另一個問題是您可能更改了商品順序。
解決這個問題的最干凈的方法是使用key引數:默認情況下它是相等的專案索引。
完美地您的專案有一個id,但您也可以key根據任何其他專案屬性構建。當key自上次重組以來不一樣時 -AndroidView將被重新創建。ps 當你不需要索引時,你可以使用items代替itemsIndexed:
LazyColumn {
items(list, key = { it.id }) { item ->
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/371517.html
標籤:安卓 科特林 android-jetpack-compose
上一篇:四分之一計數器(kotlin)
