【发布时间】:2019-09-04 10:36:21
【问题描述】:
我遇到了一个奇怪的问题。我通过工厂设计模式将视图模型绑定到我的布局。当我构建推断和预期视图模型之间存在差异时。
我的视图模型类
class SleepTrackerViewModel(
val database: SleepDatabaseDao,
application: Application) : AndroidViewModel(application) {
private var viewModelJob = Job()
private val uiScope = CoroutineScope(Dispatchers.Main + viewModelJob)
var alarmList = database.getAllAlarms()
override fun onCleared() {
super.onCleared()
viewModelJob.cancel()
}
fun onStartTracking() {
uiScope.launch {
val newNight = AlarmModel()
insert(newNight)
}
}
private suspend fun insert(night: AlarmModel) {
withContext(Dispatchers.IO) {
database.insert(night)
}
}
}
所以当我每次尝试在片段中分配视图模型时,它都会显示预期和推断的视图模型不同的错误
我的 XML 文件
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="viewModel"
type="com.example.android.trackmysleepquality.Fragments.SleepTrackerViewModel" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- TODO: Update blank fragment layout -->
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
app:listData="@{viewModel.alarmList}" />
</LinearLayout>
</layout>
我的工厂班
class SleepTrackerViewModelFactory(
private val dataSource: SleepDatabaseDao,
private val application: Application) : ViewModelProvider.Factory {
@Suppress("unchecked_cast")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(SleepTrackerViewModel::class.java)) {
return SleepTrackerViewModel(dataSource, application) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
【问题讨论】:
-
你是如何在片段中实例化 SleepTrackerViewmodel 的?提供该代码。
-
不,在工厂我已经添加了工厂代码,请检查
-
能否也提供您的片段代码。
-
片段代码已经存在
-
我需要查看您的 SleepTrackerFragment 类。添加那个
标签: android kotlin android-databinding