Jetpack 撰写的新手,有人可以解释为什么当我在 LazyRow 中选择一个项目并将该 url 传递给 Image 时,它会再次重新组合整行吗?我应该如何使用 movieSelector 变量?
@Composable
fun MovieHorizontalCarousel(viewModel: MovieViewModel = MovieViewModel()) {
val movies: LazyPagingItems<Movie> = viewModel.movies.collectAsLazyPagingItems()
Column(
modifier = Modifier
.fillMaxSize()
) {
val movieSelector = remember { mutableStateOf("") }
Carousel(
movies = movies,
onMovieSelected = { url -> movieSelector.value = url },
Modifier
.fillMaxWidth()
.height(100.dp)
)
MoviePreview(
movieSelector.value,
modifier = Modifier
.fillMaxWidth()
.weight(1f)
)
}
}
@Composable
fun MoviePreview(url: String,
modifier: Modifier = Modifier) {
AsyncImage(
modifier = modifier
.fillMaxSize()
.background(Purple40),
model = url,
contentDescription = "Preview"
)
}
@Composable
fun Carousel(movies: LazyPagingItems<Movie>,
onMovieSelected: (String) -> Unit,
modifier: Modifier = Modifier) {
LazyRow(
modifier = modifier
.wrapContentSize()
.background(Purple80),
//horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
items (
count = movies.itemCount,
key = { index -> movies[index]?.id ?: index }
//key = movies.itemKey{ item -> item.id }
) { index ->
movies[index]?.let {
MovieCarouselItem(movie = it,
onMovieSelected = onMovieSelected)
}
}
}
}
@Composable
fun MovieCarouselItem (movie: Movie,
onMovieSelected: (String) -> Unit,
modifier: Modifier = Modifier) {
AsyncImage(
modifier = modifier
.size(81.dp)
.clickable {
onMovieSelected("https://image.tmdb.org/t/p/w500${movie.posterPath}")
},
model = "https://image.tmdb.org/t/p/w500${movie.posterPath}",
contentDescription = "Movie Thumbnail" ,
contentScale = ContentScale.Crop,
placeholder = painterResource(id = R.drawable.photo)
)
}
我正在尝试显示用户从惰性行中选择的图像,它更新了图像,但也重新组成了电影列表。
假设问题是整个列是可重新启动的最近范围,请参阅:https://www.jetpackcompose.app/articles/donut-hole-skipping-in-jetpack-compose
为了测试这一点,尝试用盒子或其他东西包装 MoviePreview(在 MovieHorizontalCarousel 中),然后看看会重新组合什么