我正在尝试实例化一个包含 init 块的viewModel
类,我正在尝试在其中发送 Get 请求。问题是当我尝试在我的 Fragment 类中实例化这个类时,我收到此错误,我不知道为什么。也许构造函数的上下文会是问题所在?谢谢:
视图模型类
class BooksFragmentViewModel(c : Context) : ViewModel() {
lateinit var cont: Context
var books: MutableLiveData<MutableList<BookItem>> = MutableLiveData<MutableList<BookItem>>()
var triggerAddBook = MutableLiveData<Boolean>()
var triggerDeleteBook = MutableLiveData<Boolean>()
var triggerEditBook = MutableLiveData<Boolean>()
var bookRepo: BookRepository = BookRepository()
var bookItemAdd: BookItem? = null
var bookItemDelete: BookItem? = null
var bookItemEdit : BookItem? = null
var bookNew: LiveData<BookItem> = Transformations.switchMap(triggerAddBook) {
if (it != null && it)
addBook()
else
null
}
init {
books = bookRepo.booksGetRequest(c)
}
片段类
class BooksFragment : Fragment(), BooksAdapter.OnDeleteBtnClicked, BooksAdapter.OnEditBtnClicked {
lateinit var booksModel: BooksFragmentViewModel
var position: Int = 0
private var adapter: BooksAdapter = BooksAdapter(this, this)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_books, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
booksModel = ViewModelProvider(requireActivity()).get(BooksFragmentViewModel::class.java)
booksLoading_progressBar.visibility = View.VISIBLE
var c: Context? = context
if (c != null) {
booksModel.setContext(c)
}
这个问题确实是因为带有参数的主要构造函数。您要求ViewModelProvider
创建BooksFragmentViewModel
类的实例,但提供程序对预期的参数一无所知。
这是一篇关于该主题的帖子。
如何解决问题?
- 如果可能,请删除所有主要构造函数参数。这应该是最简单的方法;
- 创建将处理视图模型创建的
ViewModelProvider.Factory
。
第一个选项很清楚,但对于第二个选项,您应该执行以下操作。
创建ViewModelProvider.Factory
:
class BooksFragmentViewModelFactory (val context: Context) :
ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(BooksFragmentViewModel::class.java)) {
return BooksFragmentViewModel(context) as T
} else {
throw RuntimeException("Failed to create instance of the ${modelClass.simpleName}")
}
}
}
使用工厂ViewModelProvider
:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val bookViewModelFactory = BooksFragmentViewModelFactory(requireContext())
booksModel = ViewModelProvider(requireActivity(), bookViewModelFactory).get(BooksFragmentViewModel::class.java)
booksLoading_progressBar.visibility = View.VISIBLE
}
有关更多说明,请查看Google的此Codelab(步骤8)。有足够的示例来了解如何使用视图模型工厂的基础知识。
如果你有一个带有参数的ViewModel
(比如你的例子中的上下文),那么你需要使用Factory
将任何参数传递给该ViewModel
booksModel = ViewModelProvider(this,object :
ViewModelProvider.Factory{
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return booksModel(requireActivity()) as T
}
}).get(booksModel::class.java)