LazyColumn 当选择将 url 传递给 AsyncImage 时重新组合

问题描述 投票:0回答:1

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)
    )
}

我正在尝试显示用户从惰性行中选择的图像,它更新了图像,但也重新组成了电影列表。

android android-jetpack-compose lazy-loading lazycolumn
1个回答
0
投票

假设问题是整个列是可重新启动的最近范围,请参阅:https://www.jetpackcompose.app/articles/donut-hole-skipping-in-jetpack-compose

为了测试这一点,尝试用盒子或其他东西包装 MoviePreview(在 MovieHorizontalCarousel 中),然后看看会重新组合什么

© www.soinside.com 2019 - 2024. All rights reserved.