This example show how to declare State Variable in one View and then use it to call another View which should change it.
View needs to be called with additional Lambda expression which is used to make the change to State Variable.
This is because Kotlin doesn't support in-out parameters (like SwiftU does, so we need this workaround).
MainActivity.kt
package com.example.testcompose
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.Text
import androidx.compose.foundation.layout.Column
import androidx.compose.material.Button
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.setContent
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val count = remember { mutableStateOf(0) }
Column {
Text("Button was clicked ${count.value} times")
Counter(count.value) { newCount -> count.value = newCount }
}
}
}
}
@Composable
fun Counter(count: Int, updateCounter: (Int) -> Unit) {
Button({ updateCounter(count+1) }) { Text("Click me") }
}
Output