在创建LazyColumn布局时,是否有一种方法可以将项源(即Array<Starters>)修改为其他东西,以便我可以将Array<Starters>重用为来自不同数组的不同项集?
@Composable
fun MyLazyColumn(lazyItems: Array<Starters>,
onClickItem: (Starters) -> Unit
) {
LazyColumn() {
items(lazyItems) { choice -> Row() { Text(text = stringResource(id = choice.textResId)) } }
}
}
Scaffold(
content = {
MyLazyColumn(lazyItems = arrayOf(Starters.Canapes,...), onClickItem = startersClickListner)
}
)发布于 2022-06-04 14:49:02
您可以通过为调用方提供机会,通过@Composable函数回调使用他想要的可组合项来创建泛型lazyColumn。
例:
@Composable
fun <T> MyLazyColumn(
lazyItems: Array<T>,
onClickItem: (T) -> Unit,
item: @Composable RowScope.(item: T) -> Unit,
) {
LazyColumn() {
items(lazyItems) { choice ->
Row(
modifier = Modifier.clickable(onClick = { onClickItem(choice) })
) {
item(choice)
}
}
}
}在你的脚手架上:
Scaffold(
content = {
MyLazyColumn<Starters>(
lazyItems = arrayOf(Starters.Canapes, ...),
onClickItem = startersClickListner
) {
Text(text = stringResource(it.textResId) )
}
}
)发布于 2022-06-04 15:09:39
迪纳摩茨给出的答案可能是解决这一问题的最“撰写”方法。但是,如果您希望提供给该列的所有东西都有它们实现的公共父级或接口,您可以这样做以获得更多的代码重用。
interface Choice {
val textResId: Int
}
@Composable
fun <T : Choice> ChoiceColumn(
choices: Array<T>,
onChoiceClick: ((T) -> Unit) = { }
) {
BasicLazyColumn(choices, onChoiceClick) {
Text(stringResource(it.textResId))
}
}
@Composable
fun <T> BasicLazyColumn(
choices: Array<T>,
onItemClick: ((T) -> Unit) = { },
itemBuilder: @Composable LazyItemScope.(item: T) -> Unit
) {
LazyColumn {
items(choices) { choice ->
Row(Modifier.clickable {
onItemClick(choice)
}) {
itemBuilder(choice)
}
}
}
}https://stackoverflow.com/questions/72500589
复制相似问题