@HiltAndroidApp
class App: Application() { ... }
@AndroidEntryPoint
class MainActivity: ComponentActivity() {
val vm: CustomViewModel = viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(....)
setContent {
AppTheme {
CustomScreen(vm = vm)
}
}
}
}
@HiltViewModel
class CustomViewModel: ViewModel() { ... }
@Composable
fun CustomScreen(vm: CustomViewModel) { ... }
从MainActiviy用viewModels()方法获取CustomViewModel后传给CustomScreen没有问题,但是从CustomScreen用viewModel()方法获取CustomViewModel就会报错:
@AndroidEntryPoint
class MainActivity: ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(....)
setContent {
AppTheme {
CustomScreen()
}
}
}
}
@Composable
fun CustomScreen(vm: CustomViewModel = viewModel()) { ... }
希望能从composable fun中直接获取CustomViewModel