Android: Passing objects to custom views with databinding

Update: There's now a [much, much simplier version of this](https://newfivefour.com/android-databinding-binding-pass-object-to-customview.html).
This is a bit voodoo, but that said... Let's say you include something like this as a static method anywhere in your codebase.

public static void setThing(View v, Object s) {
  Log.d("A log, innit", "Called setThing");

Note that the method name setThing is derived from app:thing. And the first parameter is a View and the second is an Object.
And then, in a databinding layout file, have something like

<layout xmlns:android="http://schemas.android.com/apk/res/android"

Then the above static method will be called when we try to set the app:thing attribute.
If in your static method you have something like this:

CustomViewDatabindingSettable st = (CustomViewDatabindingSettable) v;

Then, providing your custom view implements CustomViewDatabindingSettable, you can call passedDataBindingObject passing through the databound variable.
For example, your custom view could be:

public class ListView extends FrameLayout implements CustomViewDatabindingSettable {
  public void passedDataBindingObject(Object o) {
    Log.d("HIYA", "We're in passedDataBindingObject: " + o);
    // Now do something with the data bound object.

Databinding and 'instant run' seems to mess up the autogeneration sometimes, in Android Studio 2.0 beta anyhow.
I had to uninstall the project from the device occassionally to remove dead code.

android android-databinding android-custom-views

Edit on Github!

comments powered by Disqus