0
\$\begingroup\$

I'm new to Kotlin, not so new to Java and Android development. But willing and trying to make a switch. I've wrote a simple validator for EditText and was wondering if there is a way to write it more compact with lambdas.

textMTU.addTextChangedListener(object : EditTextValidator(textMTU) {
    override fun validate(textView: EditText, text: String) {
        val textToInt = if (text.isEmpty()) 0  else text.toInt()
        if (textToInt < 1280 || textToInt > 1500) {
            textView.error = getString(R.string.errorTroubleshoot)
        }
        else {
            textView.error = null
            val input = if (textMTU.rawText.isEmpty()) defaultSize else textMTU.rawText.toInt()
            if (input in 1281..1499) {
                prefs.mtuSize = input
            }
        }
    }

EditTextValidator here is simply extended TextWatcher without beforeTextChanged and onTextChanged methods

\$\endgroup\$
5
\$\begingroup\$

First of all, make attention - your code twice convert and check value. Suppose it's not efficient. Another tiny problem - 1280 and 1500 values is not change prefs.mtuSize…

My code:

class MainActivity : AppCompatActivity() {
    val TAG = MainActivity::class.simpleName.toString()

    private val defaultSize = 1500
    private var prefsMtuSize: Int = defaultSize

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val textMTU = findViewById<EditText>(R.id.textMTU)

        // Extension function
        textMTU.addTextChangedListener { text ->
            val textToInt = try { text.toInt() } catch (e: NumberFormatException) { 0 }
            if (textToInt in 1280..1500) { // 1280 <= textToInt <= 1500
                textMTU.error = null
                prefsMtuSize = textToInt
            } else {
                textMTU.error = getString(R.string.errorTroubleshoot)
                prefsMtuSize = defaultSize
            }
            Log.i(TAG, "prefsMtuSize = $prefsMtuSize")
        }
    }
}

private fun EditText.addTextChangedListener(testFunction: (text: String) -> Unit) {
    addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
            testFunction(s.toString())
        }
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { }
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { }
    })
}
\$\endgroup\$
  • \$\begingroup\$ Looks cleaner, thanks for your time answering :) \$\endgroup\$ – Datenshi Apr 19 '18 at 10:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.