如何在 Jetpack Compose 中使用 Viewmodel
How to use Viewmodel with Jetpack compose
我正在尝试将 ViewModel
与 Jetpack Compose 一起使用,
通过增加数字。
但它不起作用。也许我没有以正确的方式使用视图模型。
这是我的主要 Activity 代码
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Greeting()
}
}
}
@Composable
fun Greeting(
helloViewModel: ViewModel = viewModel()
) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxSize()
) {
Text(
text = helloViewModel.number.toString(),
fontSize = 60.sp,
fontWeight = FontWeight.Bold
)
Button(onClick = { helloViewModel.addNumber() }) {
Text(text = "Increment Number ${helloViewModel.number}")
}
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
JetpackcomposepracticeTheme {
Greeting()
}
}
这是我的视图模型 class。
与 xml 配合使用效果很好。
如何创建视图模型的对象:
class ViewModel: ViewModel() {
var number : Int = 0
fun addNumber(){
number++
}
}
当一些具有可变状态值的容器发生变化时,Compose 可以重新组合。您可以使用 mutableStateOf()
、mutableStateListOf()
等手动创建它,或者通过包装 Flow
/LiveData
.
class ViewModel: ViewModel() {
var number : Int by mutableStateOf(0)
private set
fun addNumber(){
number++
}
}
我建议你从 state in compose documentation, including this youtube video 开始,它解释了基本原理。
我正在尝试将 ViewModel
与 Jetpack Compose 一起使用,
通过增加数字。
但它不起作用。也许我没有以正确的方式使用视图模型。
这是我的主要 Activity 代码
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Greeting()
}
}
}
@Composable
fun Greeting(
helloViewModel: ViewModel = viewModel()
) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.fillMaxSize()
) {
Text(
text = helloViewModel.number.toString(),
fontSize = 60.sp,
fontWeight = FontWeight.Bold
)
Button(onClick = { helloViewModel.addNumber() }) {
Text(text = "Increment Number ${helloViewModel.number}")
}
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
JetpackcomposepracticeTheme {
Greeting()
}
}
这是我的视图模型 class。
与 xml 配合使用效果很好。
如何创建视图模型的对象:
class ViewModel: ViewModel() {
var number : Int = 0
fun addNumber(){
number++
}
}
当一些具有可变状态值的容器发生变化时,Compose 可以重新组合。您可以使用 mutableStateOf()
、mutableStateListOf()
等手动创建它,或者通过包装 Flow
/LiveData
.
class ViewModel: ViewModel() {
var number : Int by mutableStateOf(0)
private set
fun addNumber(){
number++
}
}
我建议你从 state in compose documentation, including this youtube video 开始,它解释了基本原理。