我有从文本输入中检索到的文本值。我想让用户不要填写这些输入。但是,如果用户尚未填写一个或多个值,我想显示这些输入的默认值。
我有一个数据类,看起来像这样:
@Parcelize
data 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 itself
fun createProfile(
firstName: String = "John",
lastName: String = "Doe",
description: String = "Default Description",
imageUri: String = ""
) {
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个参数。我可以传递较少的值,因为我有可选参数,但是如何根据值是否非null或空将条件传递给createProfile
。我当然可以为每个值创建检查,但是最好的方法是什么?更新
我想我对最初的问题不够清楚,因为我不仅将值从文本输入传递到
createProfile
。 profileImageUri
是Uri?
类型的类变量,最初设置为null
。用户可以选择一个图像,并使用图像数据更新此变量。我将图像数据作为String传递和存储的原因是因为所有配置文件数据也都保存到了Firestore中,因此Strings更易于使用。
最佳答案
与您自己的答案相比,我将创建一个辅助函数
fun CharSequence?.ifNullOrEmpty(default: String) = if (this.isNullOrEmpty()) default else this.toString()
并用作viewModel.createProfile(
etFirstName.text.ifNullOrEmpty("John"),
etLastName.text.ifNullOrEmpty("Doe"),
etProfileDescription.text.ifNullOrEmpty("Default Description"),
profileImageUri.ifNullOrEmpty("Default Uri")
)
编辑:鉴于更新,我会考虑fun Any?.ifNullOrEmpty(default: String) =
if (this == null || (this is CharSequence && this.isEmpty()))
default
else
this.toString()
关于android - 如果不为null或为空,则将值作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63217448/