当我尝试使用数据绑定进行操作时,未填充MutableLiveData值。
当我在String之类的主要对象中使用MutableLiveData时,它可以正常工作。但是,如果我尝试与自定义对象一起使用,则MutableLiveData#value会为空
class MyViewModel(application: Application) : AndroidViewModel(application) {
val data: LiveData<Model> = MutableLiveData<Model>()
fun save() {
// ** ERROR HERE - At this point data.value is NULL
data.value?.let { Repository().insert(it) }
}
}
<?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"
xmlns:custom="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="viewModel"
type="<my_path>.ViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/text"
android:layout_width="0dp"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="parent"
android:text="@={viewModel.data.name}"/>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
@Entity
data class Model(
@PrimaryKey(autoGenerate = true) var uid: Long? = -1,
@ColumnInfo(name = "name") var name: String? = "",
...
)
class RegisterActivity : AppCompatActivity() {
private val viewModel by lazy { MyViewModel(application) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding: ActivityRegisterBinding = DataBindingUtil.setContentView(this, R.layout.activity_register)
binding.viewModel = viewModel
binding.executePendingBindings()
}
}
在MyViewModel#save处获取MutableLiveData#value以保存数据,该值将返回null。
答案 0 :(得分:0)
我认为数据绑定不能以这种开箱即用的方式工作。一些替代方法是:
LiveData
,并使用MediatorLiveData
订阅它们以更新您的Model
实例Observable
方法中声明多个Model
字段来存储数据,收集数据并构造一个save()
实例