Skip to content

Instantly share code, notes, and snippets.

@a11n
Last active April 26, 2019 08:01
Show Gist options
  • Save a11n/16ffe69d597ecbf2ef9e to your computer and use it in GitHub Desktop.
Save a11n/16ffe69d597ecbf2ef9e to your computer and use it in GitHub Desktop.
Android bidirectional data-binding
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
>
<data>
<import type="your.package.name.Variables"/>
<variable
name="name"
type="String"
/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:text="@{@string/hello_world(name)}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:bind="@{Variables.name}"
/>
</LinearLayout>
</layout>
public class DataBinding {
@android.databinding.BindingAdapter("bind")
public static void addTextChangedListener(EditText view, final int variable) {
final ViewDataBinding binding = DataBindingUtil.findBinding(view);
view.addTextChangedListener(new TextWatcher() {
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override public void onTextChanged(CharSequence s, int start, int before, int count) {
binding.setVariable(variable, s.toString());
binding.executePendingBindings();
}
@Override public void afterTextChanged(Editable s) {
}
});
}
}
<resources>
<string name="hello_world">Hello %s!</string>
</resources>
/**
* This class is used for dynamic binding.
*
* The generated BR class could not be used in layouts directly.
* This class acts as wrapper in order to used binding ids in layouts.
*/
public class Variables {
public final static int name = BR.name;
}
@mdzaki7
Copy link

mdzaki7 commented Apr 18, 2016

Can you please post the your mainactivity class of this project...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment