binding - Android: Two-way databinding -
i trying 2 way databinding on android application. have set application bind data ui don't know how can update data model when edittext text changed.
i think of creating extended edittext override focus , textchanged can detect text changed , focus validation. how can know data object dealing with.
i tried using app:addtextchangelistener passing function return textwatcher in layout.xml received nullpointerexception.
does know how two-way databinding on android?
you can implement ontextchangemethod in data object
public void ontextchanged(charsequence newtext, int start, int before, int count) { setstringfield(newtext.tostring()); }
and add
<edittext ... android:ontextchanged="@{data.ontextchanged}" />
so, data updated every time text changed. in addition, if display yourfield on ui should observablefield.
public class data { private observablefield<string> stringfield = new observablefield<>(); public void setstringfield(string changingtext) { stringfield.set(changingtext); } public observablefield<string> getstringfield() { return stringfield; } public void ontextchanged(charsequence newtext, int start, int before, int count) { setstringfield(newtext.tostring()); } }
all layout looks this:
<layout xmlns:android="http://schemas.android.com/apk/res/android"> <data> <variable name="data" type="your.package.data" /> </data> <linearlayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <edittext android:id="@+id/username" android:layout_width="wrap_content" android:layout_height="wrap_content" android:ontextchanged="@{data.ontextchanged}" /> <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{data.stringfield}" /> </linearlayout> </layout>
Comments
Post a Comment