android - 如果不为null或为空,则将值作为参数传递

标签 android kotlin

我有从文本输入中检索到的文本值。我想让用户不要填写这些输入。但是,如果用户尚未填写一个或多个值,我想显示这些输入的默认值。
我有一个数据类,看起来像这样:

@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。我当然可以为每个值创建检查,但是最好的方法是什么?
更新
我想我对最初的问题不够清楚,因为我不仅将值从文本输入传递到createProfileprofileImageUriUri?类型的类变量,最初设置为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/

相关文章:

android-studio - Jetpack Compose 方法实现未显示(Ctrl 在悬停时不突出显示功能)

具有 2 种 View 类型的 kotlin recyclerview

android - 如何在不使用 Gradle 复制 jar 的情况下将一个模块的源包含在另一个模块中?

c# - 在 C# 中使用数组填充 Xaml

java - 安卓+Appium : Scroll inside ListView to specific position and click on it

android - Android 应用程序中的 Google Plus key : What Key?

android - Jetpack compose 中的 onPressIn 和 onPressOut

android - react 原生安卓 "Program type already present: com.reactnativecommunity.asyncstorage.AsyncLocalStorageUtil"

android - 并行运行两个 AsyncTaskLoader

android - 使用自定义 Anko 布局 DSL 关闭警告对话框