Listening fields on views
Once we're in the Android™ environment it is obvious that we'll want, sooner or later, show some values contained in fields to the user. If you're an Android developer you'll already know that the UI is made of View
s.
Every View
instance has an extension function asLifecycleOwner()
that will return a special LifecycleOwner
that will be attached to the view. This LifecycleOwner
will be aware of the attached status of the view, so listeners will automatically be stopped when the view detaches and restarted when it reattaches, in order to avoid useless computations.
Since most of the times we'll want to change the UI from the listeners, there is also the asUIThreadLifecycleOwner()
that will automatically call the listeners on the UI thread.
Recalling the page about lifecycles we can attach to this instance listeners of fields, like so:
val tv = TextView(context)
tv.asUIThreadLifecycleOwner().listen(movie.name) { //Will be called on the UI thread
tv.setText(it)
}
TextView tv = new TextView(getContext());
ViewListenUtils.asUIThreadLifecycleOwner(tv).listen(movie.name, name -> { //Will be called on the UI thread
tv.setText(name);
});
This method of binding fields to views is the most low-level one: if you only need to change the state of the view the suggested method is to use view states.
Simple utility functions exist in order to avoid calling the asUIThreadLifecycleOwner()
method each time:
val tv = TextView(context)
tv.listen(movie.name) { //Will be called on the UI thread
tv.setText(it)
}
TextView tv = new TextView(getContext());
ViewListenUtils.listen(tv, movie.name, name -> { //Will be called on the UI thread
tv.setText(name);
});
The listen()
extension functions in views are semantically equivalent to the listen()
functions in LifecycleOwner
.