簡體   English   中英

使用 LazyRow 或 Column 時如何使項目出現在屏幕中央 Jetpack Compose?

[英]How to make item appear in the center of the screen Jetpack Compose when using LazyRow or Column?

我一直在努力使 LazyRow 上的第一項在應用程序打開后立即位於屏幕中間。 一旦滾動,捕捉行為就會起作用,但是當應用程序最初打開時,第一個項目不在頁面的中心。

帶有 snapper 和無限滾動的 LazyRow

@OptIn(ExperimentalSnapperApi::class)
@Composable
fun CircularList(
    data: List<SingleBox>,
    modifier: Modifier = Modifier,
    isEndless: Boolean = true
) {
    val listState = rememberLazyListState(
        if (isEndless) Int.MAX_VALUE / 2 else 0
    )

val configuration = LocalConfiguration.current

val screenWidth = configuration.screenWidthDp.dp
val contentPadding = PaddingValues(horizontal = screenWidth / 2) //This moves starting point of item horizontally
BoxWithConstraints {
    LazyRow(
        state = listState,
        modifier = modifier,
        contentPadding = contentPadding,
        flingBehavior = rememberSnapperFlingBehavior(listState, SnapOffsets.Center, snapIndex = { _, startIndex, targetIndex ->
            targetIndex.coerceIn(startIndex - 7, startIndex + 7) //This snaps item to center of page when LazyRow stops moving
        })

    )
    {
        items(
            count = if (isEndless) Int.MAX_VALUE else data.size, //This makes it scroll infinitly
            itemContent = {
                val index = it % data.size
                CustomItem(data[index])    // item composable
            },

        )
    }

}

}

打開后的樣子在此處輸入圖像描述

打開應用程序時的外觀在此處輸入圖像描述

我認為這里最好的選擇是Accompanist Pager Library

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM