简体   繁体   English

使用 LazyRow 或 Column 时如何使项目出现在屏幕中央 Jetpack Compose?

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

I have been trying to make it so that the first item on a LazyRow is centered in the middle of the screen as soon as the app is opened.我一直在努力使 LazyRow 上的第一项在应用程序打开后立即位于屏幕中间。 The snapping behavior works once it is scrolled, but when the app is initially opened, the first item is not centered on the page.一旦滚动,捕捉行为就会起作用,但是当应用程序最初打开时,第一个项目不在页面的中心。

LazyRow with snapper and infinite scrolling带有 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
            },

        )
    }

}

} }

How it looks when opened打开后的样子在此处输入图像描述

How it should look when app is opened打开应用程序时的外观在此处输入图像描述

我认为这里最好的选择是Accompanist Pager Library

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM