Data Binding inside Anko Components ? Why not.
Oh you sweet sweet thing — ObservableProperty. Kotlin is ♥️
Let’s first see where we will get with this. 23 lines of code, and magical data binding is here in Anko Layouts.
So what gives ? Well, we need the following things to get here.
- Kotlin’s
ObservableProperty
delegate. - Adding an inline extension function to TextView
ObservableProperty and what it means ?
One thing, I keep reminding people every other day is, Kotlin isn’t any sort of black magic. When using with Android/Java Kotlin is nothing more than some extra-sweet syntactic sugar. So what is ObservableProperty
, well, nothing supremely superior to Java Observables or RxJava observables. But, there are some niceties. You should probable check these excellent blog posts out too [1][2]
So I extend ObservableProperty
and create a StandardObservableProperty
which has a value (which is the backing field containing my data) and we can add valueChangeListeners
Now we need the helloworld = hello + world
effect, for which I created an ObservableReducer
The bindString
extension
Next what we need is the bindString
extension in TextViews that lets me do these
So what we add extension functions that binds a StandardObservableProperty
to a textview. When the observable changes, we update the text in textview, and when the TextWatcher
in the TextView is updated, we update the Observable. Keep in mind the setSelection(start+count
line, because that makes sure our cursor does not jump around on the screen.
Now we can use this in our Anko layout. Simply use bindString()
to attach an ObservableProperty
into a textual field.
Since the ObservableReducer
is also extended from StandardObservableProperty
it can also be passed into a `bindString` call.
And voila, we have our 23-line magical code here.
You might want to check out our Android courses that I and Harshit Dwivedi run at https://online.codingblocks.com 😊 to catch more Android and Kotlin tips and tricks.
Also give us a follow on https://youtube.com/codingblocksindia
External Links
[Source Code]
[1]
[2]