Con*_*nor 6 lambda android kotlin android-jetpack android-jetpack-compose
在以下网址的 Android 开发人员文档中:https ://developer.android.com/jetpack/compose/mental-model#recomposition
有一个可组合函数,如下所示:
@Composable
fun ClickCounter(clicks: Int, onClick: () -> Unit) {
Button(onClick = onClick) {
Text("I've been clicked $clicks times")
}
}
Run Code Online (Sandbox Code Playgroud)
文中提到,这会生成一个元素,每次单击该元素都会更新其被单击的次数。然而,看看它,似乎需要一个 lambda 函数来做到这一点。
当我尝试将其放入 SetContent 函数时,我得到以下结果:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
WorkTimerTheme {
Conversation(SampleData.conversationSample)
ClickCounter(clicks = 0) {
//Insert My Function Here
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
该评论//Insert My Function Here是我添加的。我认为在其中我必须放置一个 Lambda 来更新可组合项的点击值,但我不知道要放置什么。有谁知道写这个的可接受的方式?
您需要MutableState触发重组并remember{}在重组发生时保留以前的值。
我问了一个关于它的问题,我的问题包含了你问题的答案。
@Composable
fun MyScreenContent(names: List<String> = listOf("Android", "there")) {
val counterState = remember { mutableStateOf(0) }
Column(modifier = Modifier.fillMaxHeight()) {
Counter(
count = counterState.value,
updateCount = { newCount ->
counterState.value = newCount
}
)
}
}
@Composable
fun Counter(count: Int, updateCount: (Int) -> Unit) {
Button(
onClick = { updateCount(count + 1) },
) {
Text("I've been clicked $count times")
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3484 次 |
| 最近记录: |