【发布时间】:2021-09-23 10:01:15
【问题描述】:
我正在尝试在可组合函数中使用我的 hilt viewModel,但我不断收到错误消息:
“java.lang.RuntimeException:无法创建 com.example.tryingtogettheviewmodeltowork.MainViewModel 类的实例”
我在我的 viewModel 中使用简单的刀柄注入来复制我在实际工作的应用程序上遇到的错误。 Android 文档说,在可组合函数中无需执行任何其他操作即可使用 hilt viewModel (https://developer.android.com/jetpack/compose/libraries#hilt),但是每次尝试其他解决方案时都会遇到相同的错误。
我的 viewModel 类:
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class MainViewModel @Inject constructor(
val someInt: Int
): ViewModel(){
init{
println(someInt)
}
// Mutable Live data for storing the value of the username entry field
private var _username = MutableLiveData("")
val username: LiveData<String> =_username
// Function for changing the value of the username entry field
fun onUsernameChange(it: String){
_username.value = it
}
}
我的具有可组合功能的 MainActivity 类:
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.MaterialTheme
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.tryingtogettheviewmodeltowork.ui.theme.TryingToGetTheViewModelToWorkTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
TryingToGetTheViewModelToWorkTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
MainScreen()
}
}
}
}
}
@Composable
fun MainScreen(viewModel: MainViewModel = androidx.lifecycle.viewmodel.compose.viewModel()) {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
val userName: String by viewModel.username.observeAsState("")
OutlinedTextField(
value = userName,
onValueChange ={
viewModel.onUsernameChange(it)
},
label = {
Text(text = "User Name")
}
)
}
}
【问题讨论】:
标签: android kotlin dependency-injection android-jetpack-compose dagger-hilt