【发布时间】:2021-07-14 00:51:05
【问题描述】:
我启动了一个简单的 Android 应用来使用 Compose UI,并从 Google Developers 页面获取了一段关于如何显示带有粘性标题的列表的代码。
我实现了代码和其他一些数据模型类,一切正常。它编译并构建,我看到我的撰写预览按预期工作。第二天回到我的电脑,打开 Android Studio,现在我在 PlantList 函数内的 grouped.forEach 语句上遇到编译时错误。 Android Studio 建议我为 Map
Type mismatch.
Required:
(Char, List<Plant>) → Unit
Found:
(Char) → Unit
Expected 2 parameters of types Char, List<Plant>
Destructuring declaration initializer of type Char must have a 'component2()' function
相关代码如下。让我难过的是前几天它还在同一台计算机上工作,当我在那里检查代码时它仍然可以在我的另一台计算机上工作。我认为我的开发环境没有任何变化。
布局.kt:
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun PlantsList(grouped: Map<Char, List<Plant>>) {
Column {
TopAppBar(
title = { Text("My Plant List") },
)
LazyColumn {
grouped.forEach { (initial, plantsForInitial) ->
stickyHeader {
CharacterHeader(initial)
}
items(plantsForInitial) { plant ->
PlantListItem(plant)
}
}
}
}
}
@Composable
fun PlantListItem(plant: Plant) {
Row(verticalAlignment = Alignment.CenterVertically) {
Image(painter = painterResource(plant.image),
contentDescription = "An image of you plant",
modifier = Modifier.width(75.dp)
)
Column {
Text(plant.name)
Text("time to next water")
}
}
}
@Composable
fun CharacterHeader(character: Char) {
Column {
Card(Modifier.fillMaxWidth().padding(8.dp), elevation = 8.dp) {
Text(character.toString())
}
}
}
MainActivity.kt
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val orderedPlantList = returnTempPlantList().groupBy { it.name[0] }
setContent {
PlantReminderTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
PlantsList(orderedPlantList)
}
}
}
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
val orderedPlantList = returnTempPlantList().groupBy { it.name[0] }
PlantReminderTheme {
PlantsList(orderedPlantList)
}
}
Plant.kt:
data class Plant(
var id: Int,
var name: String,
var image: Int
)
数据类 PlantList(var 植物:列表)
【问题讨论】:
标签: android android-studio foreach compiler-errors android-jetpack-compose