有没有办法避免类似的TextInputEditText验证重复?

问题描述 投票:0回答:1

该片段中有5个TextInputEditText字段。第一个是字符串,其他四个是用户必须输入的Doubles。为了确保这些值有效,请检查每个字段的空度,如果值是双精度,则检查最后四个(带有双精度)。

在下面的代码中,我截断了最后2个val&fun声明,因为它们与后2个oes完全相同,除了TextInPutLayout名称(和相应的val)。

所以,我想知道是否有可能以任何方式将其缩短一些

private val enterTextFoodName = view.findViewById<TextInputLayout>(R.id.enter_food_name)
private val enterTextKcal = view.findViewById<TextInputLayout>(R.id.enter_kcal)
private val enterTextCarbs = view.findViewById<TextInputLayout>(R.id.enter_carbs)
[...]

    private fun validateValues(): Boolean {
        return (!validateFoodName()
                || !validateKcal()
                || !validateCarbs()
                [...])
    }

    private fun validateFoodName(): Boolean {
        return when {
            enterTextFoodName.editText?.text.toString().trim().isEmpty() -> {
                enterTextFoodName.error = getString(R.string.cant_be_empty)
                false
            }
            else -> {
                enterTextFoodName.error = null
                true
            }
        }
    }

    private fun validateKcal(): Boolean {
        return when {
            enterTextKcal.editText?.text.toString().trim().isEmpty() -> {
                enterTextKcal.error = getString(R.string.cant_be_empty)
                false
        }
            enterTextKcal.editText?.text.toString().trim().toDoubleOrNull() == null -> {
                enterTextKcal.error = getString(R.string.invalid_value)
                false
            }
            else -> {
                enterTextKcal.error = null
                true
            }
        }
    }

    private fun validateCarbs(): Boolean {
        return when {
            enterTextCarbs.editText?.text.toString().trim().isEmpty() -> {
                enterTextCarbs.error = getString(R.string.cant_be_empty)
                false
            }
            enterTextCarbs.editText?.text.toString().trim().toDoubleOrNull() == null -> {
                enterTextCarbs.error = getString(R.string.invalid_value)
                false
            }
            else -> {
                enterTextCarbs.error = null
                true
            }
        }
    }

[...]
android kotlin android-textinputlayout android-textinputedittext
1个回答
0
投票

您可以在Kotlin中使用扩展功能来实现它:

inline fun TextInputLayout.validateInput(messageInvalid: String? = null, validate: (String?) -> Boolean): Boolean {
    val inputText = editText?.text?.toString()?.trim()
    when {
        inputText.isNullOrEmpty() -> {
            error = context.getString(R.string.cant_be_empty)
        }

        validate(inputText) -> {
            error = messageInvalid
        }

        else -> {
            error = null
            return true
        }
    }
    return false
}

然后您可以像这样使用它:

val isCarbsValid = enterTextCarbs.validateInput(getString(R.string.invalid_value)) { it?.toDoubleOrNull() != null }
© www.soinside.com 2019 - 2024. All rights reserved.