我试图显示一个列表的图像和它的名字,其中第一列所有应包含所有的图像从列表和第二列应包含所有的名称。但是,它只在两列中显示名称,如x1c 0d1x
我希望所有这些名字都在第二列和第一列的图像。下面是我的ComposablePlayScreen的代码
//播放屏幕以练习已学习的单词
@Composable
fun PlayScreen() {
// Create a ViewModel to handle the logic and data for the Composable
val viewModel: PractiseViewModel = viewModel()
val imageInfoList = viewModel.imageInfoList.value
LazyVerticalGrid(cells = GridCells.Fixed(2)) {
items(imageInfoList.size) { index ->
ImageInfoCard(imageInfoData = imageInfoList[index])
Text(
text = imageInfoList[index].name,
modifier = Modifier
.padding(8.dp)
.background(Color.Red)
.fillMaxWidth()
.height(100.dp),
style = TextStyle(fontSize = 16.sp),
textAlign = TextAlign.Center,
)
}
}
}
fun generateImageList(): List<ImageInfoData> {
val images = listOf(
R.drawable.apple,
R.drawable.mango,
R.drawable.banana,
R.drawable.coconut,
R.drawable.orange
)
val imageNames = listOf("Apple", "Mango", "Banana", "Coconut", "Orange")
val shuffledNames = imageNames.shuffled()
return images.zip(shuffledNames) { image, name ->
ImageInfoData(image, name)
}
}
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun ImageInfoCard(imageInfoData: ImageInfoData) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
onClick = {
// Handle click event here
}
) {
Column {
Image(
painter = painterResource(id = imageInfoData.imageResId),
contentDescription = imageInfoData.name,
modifier = Modifier
.background(Color.Green)
.width(180.dp)
.height(100.dp),
contentScale = ContentScale.Inside
)
}
}
}
@Preview
@Composable
fun PlayScreenPreview() {
PlayScreen()
}
字符串
下面是PlayScreen中使用的视图模型PractiseViewModel
class PractiseViewModel:ViewModel() {
//MutableStateFlow to hold the list of ImageInfoData
private val _imageInfoList = MutableStateFlow<List<ImageInfoData>>(emptyList())
val imageInfoList:StateFlow<List<ImageInfoData>> get() = _imageInfoList
init {
viewModelScope.launch {
_imageInfoList.value = generateImageList()
}
}
}
型
下面是使用的数据类ImageInfoData
data class ImageInfoData(val imageResId:Int, val name:String)
型
我尝试过在LazyColumn中使用LazyverticalGrid和LazyColumns,但我遇到了同样的问题。
2条答案
按热度按时间m0rkklqb1#
我复制了你的代码,通过改变你给
100.dp
的文本的高度得到了这个结果,它占据了项目的所有高度。https://gist.github.com/chiragthummar/31689d97dbb5579199a1e556d21a40d9
代码输出
ecbunoof2#
你需要把物品分开比如
字符串