Two-way DataBinding in Android
source link: https://www.ravirupareliya.com/blog/two-way-databinding-in-android/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Home Android / DataBinding Two-way DataBinding in Android
Two-way DataBinding in Android
In the earlier posts we have seen how to use DataBinding, Setting custom font and Image loading. Today we will discuss about two-way DataBinding.
What is Two-way DataBinding?
Till now we have seen how to set values to xml view, but in controls like EditText we need to fetch value. In simple term two-way DataBinding is setting values to that control and fetching it after having some changes.
ObservableField
ObservableField can be used instead of extending BaseObservable class. ObservableFields are self-contained observable objects that have a single field.
There is no need to create getter setter methods when we are using ObservableFields. Now attach custom TextWatcher to get values of EditText control.
TextWatcherAdapter is custom class which extends TextWatcher. It will be used to fetch updated value of EditText.
Layout file is very simple for this, with 2 EditTexts and a button. We need to set addTextChangeListener to bind custom TextWatcher with EditText.
Here you have noticed handler.onClickLogin in a Button, that is nothing but an interface which we have binded to Button.
Finally we will write our Activity code to perform all the actions. Binding will be same as we have done earlier.
we need to set Model/Pojo class to view and set handler for onClick event. Here is full code of our MainActivity.
With this you are done with your simple login screen using DataBinding.
Download code
Update :
With the latest update of DataBinding announced in Google I/O16, you will be able to use Two-Way DataBinding with minimal number of code. You don’t need to write those listeners. Here is the thing you need to change in your xml file.
By adding = sign in your expression will support Two-Way DataBinding.
Ravi Rupareliya
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK