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

asked Apr 9, 2018 at 11:30
\$\endgroup\$

1 Answer 1

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) { }
 })
}
answered Apr 15, 2018 at 4:56
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.