我有从文本输入中检索到的文本值。我想让用户不要填写这些输入。但是,如果用户尚未填写一个或多个值,我想显示这些输入的默认值。
我有一个数据类,看起来像这样:
@Parcelizedata class Profile( val firstName: String = "", val lastName: String = "", val description: String = "", val imageUri: String = "") : Parcelable
单击时,我从ViewModel类中调用一个方法,并将当前输入值传递给该方法,然后使用Repository类将其持久化:
viewModel.createProfile(
etFirstName.text.toString(),
etLastName.text.toString(),
etProfileDescription.text.toString(),
profileImageUri.toString())// The createProfile function itselffun createProfile(
firstName: String = "John",
lastName: String = "Doe",
description: String = "Default Description",
imageUri: String = "Default Uri") {
val profile = Profile(firstName, lastName, description, imageUri)
// Persist data}在另一个片段中,我使用以下持久化数据来设置一些UI数据,如下所示:
private fun observeProfile() {
viewModel.getProfile()
viewModel.profile.observe(viewLifecycleOwner, Observer {
val profile = it
tvName.text = getString(R.string.profile_name, profile.firstName, profile.lastName)
tvDescription.text = profile.description
ivProfileImage.setImageURI(Uri.parse(profile.imageUri))
})}因此,目前createProfile需要4个参数。我可以传递较少的值,因为我有可选参数,但是如何createProfile根据值是非null还是空值有条件地将参数传递给。我当然可以为每个值创建检查,但是最好的方法是什么?
我认为你需要一个定制的setter每个字段,这样,你仍然可以通过和公正处理什么被通过,虽然我不知道这是可能的数据类,我不认为它是,除了检查每个值,我也没有想到更好的解决方案,这可能是多余的,但最简单的解决方案 – a_local_nobody