我正在尝试使用下面的jetpack compose实现水平滚动 View :

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 })
    }
}

09-28 06:15