简体   繁体   English

如果 LazyColumn 为空,则将 LazyColumn 项目推送到屏幕末尾

[英]Push a LazyColumn item to end of screen if the LazyColumn is empty

I want to add a footer to LazyColumn that only appears when all the items are scrolled, but if there are no items in the LazyColumn or no enough items to cover the whole screen, I want the footer to show at the bottom of the screen.我想向 LazyColumn 添加一个页脚,该页脚仅在滚动所有项目时出现,但如果 LazyColumn 中没有项目或没有足够的项目覆盖整个屏幕,我希望页脚显示在屏幕底部。

Since we cannot set weights in LazyColumn is there any other way to achieve this?既然我们不能在 LazyColumn 中设置权重,还有其他方法可以实现吗?

You can use the LazyListState#layoutInfo to know if the list is empty or if there is available space at the bottom.您可以使用LazyListState#layoutInfo来了解列表是否为空或底部是否有可用空间。

val state = rememberLazyListState()

val isIniatialLoading by remember {
    derivedStateOf {
        state.layoutInfo.viewportSize  == IntSize.Zero
    }
}

//Empty list or empty space
val hasEmptySpace by remember {
    derivedStateOf {
        val layoutInfo = state.layoutInfo
        val visibleItemsInfo = layoutInfo.visibleItemsInfo
        if (layoutInfo.totalItemsCount == 0) {
            true
        } else {
            val lastVisibleItem = visibleItemsInfo.last()
            val viewportHeight = layoutInfo.viewportEndOffset + layoutInfo.viewportStartOffset
            
            (lastVisibleItem.index + 1 == layoutInfo.totalItemsCount &&
                    lastVisibleItem.offset + lastVisibleItem.size < viewportHeight)
        }
    }
}

Then wrap the LazyColumn with a Column and apply the weight modifier to the list.然后用Column包装LazyColumn并将weight修饰符应用于列表。

Column(Modifier.fillMaxSize()) {

    LazyColumn(
        state = state,
        modifier = Modifier.weight(1f)
    ){
        items(itemsList) {
           //....
        }

        //Footer when the list covers the entire screen
        if (!hasEmptySpace){
            item(){
                //Footer()
            }
        }
    }
    
    // Display the Footer at the bottom of the screen if the list is empty or if there is an empty space
    if ( !isIniatialLoading && hasEmptySpace ){
       //Footer()
    }

}

在此处输入图像描述

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

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