首页 > 解决方案 > 在 ViewModel 中使用刀柄注入时无法在可组合函数中使用 ViewModel

问题描述

我正在尝试在可组合函数中使用我的 hilt viewModel,但我不断收到错误消息:

“java.lang.RuntimeException:无法创建 com.example.tryingtogettheviewmodeltowork.MainViewModel 类的实例”

我在我的 viewModel 中使用简单的刀柄注入来复制我在实际工作的应用程序上遇到的错误。Android文档说在可组合函数中不需要做任何其他事情来使用hilt viewModel(https://developer.android.com/jetpack/compose/libraries#hilt)但是每次我尝试另一个时我都会遇到同样的错误解决方案。

我的视图模型类:

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")
            }
        )

    }
}

标签: androidkotlindependency-injectionandroid-jetpack-composedagger-hilt

解决方案


我发现了我的错误。您必须将 @AndroidEntryPoint 添加到 MainActiivty 而不是尝试将其添加到可组合函数之上。


推荐阅读