Android 粘性 - 使用 jetpack 撰写的页脚:将页脚视图与表格对齐,直到达到屏幕尺寸,然后固定在底部

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

我想使用 jetpack compose 来实现这一点。

A 是行项目的可滚动列表。当 A 小于屏幕(或父级)尺寸时,B(页脚)应放置在最后一行下方。当 A + B 大于屏幕尺寸时,B 固定在底部,A 内容可滚动。我想知道是否有简单的方法可以使用 compose ConstraintLayout 来实现此目的。

android android-jetpack-compose sticky-footer android-compose-lazyfor
4个回答
17
投票

解决方案是在A中使用

Modifier.weight(1f, false)
。这是因为父元素的大小将首先被未加权的元素使用,然后剩余的空间将根据权重分配给加权的元素。请参阅此答案了解更多详细信息。


10
投票

有很多方法可以做到这一点,但最有效的方法是使用

bottomBar
View 的
Scaffold
属性。

例如:

@Composable
fun RenderContent() {
    Scaffold(
        topBar = { /* Your app bar goes here */ },
        bottomBar = { /* Anything you place in here will be stick to the bottom. */ }
    ) {
        // ... Rest of the content
        // Benefits: If you make the content scrollable and
        // the `bottomBar` composable remain on top of the content
    }
}

1
投票

如果我理解正确,您正在尝试向 LazyColmn 添加页脚视图。 JetpackCompose 中的 LazyColumn 的行为类似于本机 ListView。我将给出一个 LazyColumn 的示例,该示例在底部有一个视图(可组合),当您滚动到列表末尾时会显示该视图:

LazyColumn() {
item {
    //If you want the first item to stay always on top as you scroll use stickyHeader for this section.
    Text("This is the first item")
}
items(listItems.size) {
    Text("This is a normal list item")
}
item {
    Text("This item will behave as a footer and display at the end of the list")
}

}

希望这对某人有帮助。 谢谢


0
投票

虽然最直接的方法是使用

ConstraintLayout
我不能推荐它,因为目前存在太多错误,并且从我的经验来看它似乎不稳定。

ConstraintLayout 之外最简单的方法是使用任意容器元素来绘制子元素,例如

Scaffold
Box
。由于
Scaffold
对于如此简单的解决方法来说包含太多逻辑
,所以我每次都会选择
Box

我可以举的最简单的例子是

Box {
    LazyColumn {
        stickyHeader {

        }
        items(listOf()) {
            
        }
    }

    // doesn't have to be a Box, any element will do, such as Row/Column/...
    // the Alignment.BottomCenter is the key
    Box(modifier = Modifier.align(Alignment.BottomCenter)) {
        //This is your sticky footer Content
    }
}

我看到的唯一缺点是您必须向

LazyColumn
提供偏移量才能位于页脚“上方”。这可以这样实现:

Box {
    LazyColumn {
        stickyHeader {

        }
        items(listOf()) {

        }
        item {
            Spacer(
                modifier = Modifier.height(
                    with(LocalDensity.current) {
                        stickyFooterHeight.intValue.toDp()
                    }
                )
            )
        }
    }

    Box(
        modifier = Modifier
            .align(Alignment.BottomCenter)
            .onSizeChanged {
                stickyFooterHeight.intValue = it.height
            }
    ) {
        //...
    }
}

您可以选择将其变成一个组件,您可以轻松地再次重复使用该组件,并在

.animateContentSize
上添加
Spacer
,使其看起来无缝。

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