6

私は以下のいくつかの拡張機能関数を持っています。

fun EditText.setEmailValidationListener(): TextWatcher {
    val textWatcher = object : TextWatcher {
        override fun beforeTextChanged(text: CharSequence?, start: Int, count: Int, after: Int) { }
        override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) { }
        override fun afterTextChanged(text: Editable?) { validateEmail() }

        private fun validateEmail(): Boolean {
            if (validateEmailFormat(showError = false)) {
                getParentInputLayout()?.isErrorEnabled = false
                return true
            }
            return false
        }
    }
    addTextChangedListener(textWatcher)

    return textWatcher

}

fun EditText.setPasswordValidationListener(): TextWatcher {
    val textWatcher = object : TextWatcher {
        override fun beforeTextChanged(text: CharSequence?, start: Int, count: Int, after: Int) { }
        override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) { }
        override fun afterTextChanged(text: Editable?) { validateEmpty() }

        private fun validatePasswordText(): Boolean {
            if (validateEmptyText(showError = false)) {
                getParentInputLayout()?.isErrorEnabled = false
                return true
            }
            return false
        }
    }

    addTextChangedListener(textWatcher)

    return textWatcher
}

fun EditText.validateEmailFormat(showError: Boolean = true): Boolean 
{
    // Do something checking the Email
    return false
}

fun EditText.validatePasswordText(showError: Boolean = true): Boolean     
{
    // Do something checking the Password
    return false
}

private fun EditText.getParentInputLayout(): TextInputLayout? {
    if (parent is TextInputLayout) {
        return parent as TextInputLayout
    }
    return null
}

setEmailValidationListenerとはsetPasswordValidationListener、それぞれ使用する検証関数、つまりvalidateEmailFormatとを除いて、同じですvalidatePasswordFormat

そのため、以下のように 2 つの関数の共通コードを共通関数にリファクタリングする予定です。

fun EditText.setupTextChangeListener(validatorFunc : (showError: Boolean) -> Boolean): TextWatcher {
    val textWatcher = object : TextWatcher {
        override fun beforeTextChanged(text: CharSequence?, start: Int, count: Int, after: Int) { }
        override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) { }
        override fun afterTextChanged(text: Editable?) { validateEmpty() }

        private fun validateEmpty(): Boolean {
            if (validatorFunc(false)) {
                getParentInputLayout()?.isErrorEnabled = false
                return true
            }
            return false
        }
    }

    addTextChangedListener(textWatcher)

    return textWatcher
}

validationFunc...基本的には、パラメーターとして送信するだけです。

EditText.validateEmailFormatただし、 andEditText.validatePasswordFormatvalidationFunc関数パラメーターに送信する方法が見つかりません。

どうすればそれを達成できますか?

4

2 に答える 2