Bindroid - A Binding Framework for Android
I'll admit it -- I was spoiled by my days on the Silverlight team, playing with XAML, .NET, and databinding. When I started building Android versions of my apps, I went in with the expectation of a similarly modern, powerful UI framework, but quickly found myself frustrated by the complexity of creating UI that tracks values as they change in my application.
Unlike XAML-based UI frameworks, Android doesn't really have a standard change notification mechanism, nor does it have databinding functionality. For my apps, I found it useful to build a general-purpose framework that I could use to build really rich, responsive user experiences with minimal effort. I've decided to open-source this framework as Bindroid, in the hopes that others might find it useful as they build their apps as well.
Bindroid makes binding your UI to your data really easy. Just use a "Trackable" to implement your properties (in Java, I consider this to be a pair of methods on an object named get<Name>
and set<Name>
) like so:
public class FooModel {
// An int property named "Bar"
private TrackableInt bar = new TrackableInt(0);
public int getBar() {
return bar.get();
}
public void setBar(int value) {
bar.set(value);
}
// A String property named "Baz"
private TrackableField<String> baz = new TrackableField<String>();
public String getBaz() {
return baz.get();
}
public void setBaz(String value) {
baz.set(value);
}
}
Trackables are quite magical -- they "infect" anything they touch with observability, so that even calculated properties can be observable:
public String getBarBaz() {
int strLength = (getBaz() == null ? 0 : getBaz().length());
if ((strLength + getBar()) % 2 == 0) {
return "Baz's length + Bar was even.";
}
return String.format("Bar: %d, Baz: %s", getBar(), getBaz());
}
Once you've implemented your properties this way, binding to them is a one-liner in your Activity's onCreate()
. For example, the following line binds the Text
property of a TextView
named barBazTextView
to the BarBaz
property we just defined:
FooModel model = new FooModel();
UiBinder.bind(this, R.id.barBazTextView, "Text", model, "BarBaz", BindingMode.ONE_WAY);
As you manipulate the values of the model, barBazTextView
's text will automatically update to reflect the new value of BarBaz
. It's that simple!
I've found that whether binding to individual values or collections of values, Bindroid dramatically simplifies the process, and makes developing Android user interfaces a much more pleasant experience.
I hope you'll give it a try! You can learn more about (and get a copy of) Bindroid by visiting the GitHub repository. It's all available under the MIT License, so have at it!