2016-11-13 96 views
15

如何为Kotlin中的EditText addTextChangeListener构建lambda表达式?下面给出了一个错误:Kotlin addTextChangeListener lambda?

passwordEditText.addTextChangedListener { charSequence -> 
    try { 
     password = charSequence.toString() 
    } catch (error: Throwable) { 
     raise(error) 
    } 
} 
+1

它给出了什么错误? – voddan

回答

0

这看起来整洁:

passwordEditText.setOnEditorActionListener { 
    textView, keyCode, keyEvent -> 
    try { 
     val DONE = 6 
     if (keyCode == DONE) { 
      password = passwordEditText.text.toString() 
     } 
    } catch (error: IllegalStateException) { 
     alert("Invalid Input!", error.message as String) 
     passwordEditText.text.clear() 
    } catch (error: Exception) { 
     raise(error) 
    } 
    false 
} 
47

addTextChangedListener()需要TextWatcher这与3种方法的接口。你写的只有在TextWatcher只有1个方法的情况下才有效。我要猜测你得到的错误与你的lambda没有实现其他两种方法有关。你有两个选择前进。

1)沟拉姆达和只是使用一个匿名内部类

editText.addTextChangedListener(object : TextWatcher { 
    override fun afterTextChanged(p0: Editable?) { 
    } 

    override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { 
    } 

    override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { 
    } 
}) 

2)创建的扩展方法,以便可以使用一个lambda表达式:

fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) { 
    this.addTextChangedListener(object : TextWatcher { 
     override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { 
     } 

     override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { 
     } 

     override fun afterTextChanged(editable: Editable?) { 
     afterTextChanged.invoke(editable.toString()) 
     } 
    }) 
} 

然后使用扩展像所以:

editText.afterTextChanged { doSomethingWithText(it) } 
+2

不知道个人偏好或更好的风格,但你的扩展功能可以转换成表达式体('fun foo()= ...') –

+1

@ mEQ5aNLrK3lqs3kfSa5HbvsTWe0nIu你说得对,它可以被转换。但是,对于长于一行的函数,我喜欢使用括号来清楚标记函数在哪里启动和停止。我相信它增加了可读性,但它完全是一种风格偏好。我认为这可能是两方面的争论:) –

+0

@LEM Adane如果它帮助你,请接受这个答案。 –

0

另一种选择是KAndroid库找到here

那么你可以做这样的事情...

editText.textWatcher { afterTextChanged { doSomething() } } 

显然,这是过度使用整个库来解决你的问题,但它也配备了一个范围,消除了样板代码其它有用的扩展在Android SDK中。

相关问题