Inline onFocusChange kotlin
Solution 1
Just to clarify, there isn't really a point in creating an inline method extension. This was my initial objective but I later realized that using:
editText.setOnFocusChangeListener { view, b -> doSomething(b) }
was possible, it's inline, it's pretty and no extra work is needed
Solution 2
You simply forgot to call hasFocus
:
setOnFocusChangeListener(View.OnFocusChangeListener { view, b -> hasFocus(b) })
/\/\/\/\/\
Solution 3
This is a sweet and readable syntax:
yourEditText.setOnFocusChangeListener { _, hasFocus ->
if (hasFocus)
showSomething()
else
hideSomething()
}
Comments
-
Aerim about 2 years
I'm trying to build an inline function for
setOnFocusChangeListener
This is what I got so far:
inline fun EditText.onFocusChange(crossinline hasFocus: (Boolean) -> Unit) { setOnFocusChangeListener(View.OnFocusChangeListener { view, b -> }) }
And I use it like this
freightTimeOfDay.onFocusChange { doSomething() }
Unfortunately though it gives me no errors,
doSomething()
is never called.I'm looking for two things here:
1 - Get a param in there so I can pass it on to doSomething(). For example
freightTimeOfDay.onFocusChange { doSomething(hasFocus) }
2 - Make it work :p, as right now nothing is happening.
Update:
Seems like kotlin already has some type of inline for this
editText.setOnFocusChangeListener { view, b -> doSomething(b) }
However this isn't working for me either,
doSomething(hasFocus: Boolean)
is never called.Thanks in advance!
-
R G almost 6 yearsCan you please tell me what is "b" here?
-
xinaiz almost 6 years@R_G It's a boolean argument that indicates whether view gained focus (true) or lost focus (false)
-
Aerim about 4 yearsHi! Thanks for taking the time to answer. However I don't think the answer you gave is related. The question has already been answered