gpt4 book ai didi

android - 如何在android jetpack compose ui中实现水平滚动?

转载 作者:行者123 更新时间:2023-12-01 04:26:05 26 4
gpt4 key购买 nike

我正在尝试使用 jetpack compose 实现水平 ScrollView ,如下所示:

Pic Of what I want

但我找不到任何解决方案来设置单元格的宽度以采用 16dp 边距的屏幕宽度,这就是我得到的:

Pic Of what I'm getting

这是我的代码:

private val imageList : Array<Effect<Image>> =arrayOf(
imageResource(R.drawable.maldive),
imageResource(R.drawable.maldiveone),
imageResource(R.drawable.maldivetwo))

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
createList()
}


}

@Composable
fun createList(){
MaterialTheme() {
HorizontalScroller(){
Row(crossAxisSize = LayoutSize.Expand) {
(0..3).forEachIndexed { _, i ->
populateListItem(i)
}
}
}
}
}
@Composable
fun populateListItem(index: Int){
Column(crossAxisSize = LayoutSize.Wrap, modifier = Spacing(16.dp)) {
Card(elevation = 0.dp, shape = RoundedCornerShape(8.dp, 8.dp, 8.dp, 8.dp)) {
val im: Image = +imageList[index.rem(3)]
Container(expanded = true,height = 180.dp)
{
DrawImage(image = im)
}
}
HeightSpacer(height = 16.dp)
Text("Maldive $index",
style = +themeTextStyle { h6 })
Text("Enjoy Our $index Resort!",
style = +themeTextStyle { body2 })
}
}

最佳答案

关键是resources.displayMetrics.widthPixels,这会很神奇。用下面替换您的 populateListItem 函数,它将起作用

@Composable
fun populateListItem(index: Int) {
val padding = 16
val dm = resources.displayMetrics
val cardWidth = dm.widthPixels/dm.density - 16 * 2 // 2 is multiplied for left and right padding
Column(crossAxisSize = LayoutSize.Wrap, modifier = Spacing(padding.dp)) {
Card(elevation = 0.dp, shape = RoundedCornerShape(8.dp, 8.dp, 8.dp, 8.dp)) {
val im: Image = +imageList[index.rem(3)]
Container(width = cardWidth.dp, height = 180.dp)
{
DrawImage(image = im)
}
}
HeightSpacer(height = 16.dp)
Text("Maldive $index",
style = +themeTextStyle { h6 })
Text("Enjoy Our $index Resort!",
style = +themeTextStyle { body2 })
}
}

关于android - 如何在android jetpack compose ui中实现水平滚动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58633678/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com