Skip to content Skip to sidebar Skip to footer

Data Bindings With Custom Listeners On Custom View

I'm trying to bind an event on a custom view with the new Android data-binding library but run into an issue. Here's the relevant part of my custom view: public class SuperCustomVi

Solution 1:

@BindingMethods(@BindingMethod(type = SuperCustomView.class, attribute = "app:onToggle", method = "setOnToggleListener"))
publicclassSuperCustomViewextendsFrameLayout {
    privateOnToggleListener mToggleListener;

    publicinterfaceOnToggleListener {
        voidonToggle(boolean switchPosition);
    }

    publicvoidsetOnToggleListener(OnToggleListener listener) {
        mToggleListener = listener;
    }
    .../...
}

My hack to test code was:

publicvoidsetOnToggleListener(final OnToggleListener listener) {
    this.setOnClickListener(newOnClickListener() {
        @OverridepublicvoidonClick(View v) {
            toggle = !toggle;
            listener.onToggle(toggle);
        }
    });
}

And on my controller object:

publicclassMyController {

    private Context context;

    publicMyController(Context context) {
        this.context = context;
    }

    publicvoidtoggleStrokeLimitation(boolean switchPosition) {
        Toast.makeText(context, "Toggle" + switchPosition, Toast.LENGTH_SHORT).show();
    }
}

Yeah!! it worked

Alternatively you can use xml like:

<com.androidbolts.databindingsample.model.SuperCustomViewandroid:layout_width="match_parent"android:layout_height="match_parent"app:onToggleListener="@{controller.toggleStrokeLimitation}" />

Now no need to add @BindingMethods annotation.

Documentation says:"Some attributes have setters that don't match by name. For these methods, an attribute may be associated with the setter through BindingMethods annotation. This must be associated with a class and contains BindingMethod annotations, one for each renamed method. "

Solution 2:

You may not needBindingMethods for listen listeners on custom view if you define method name follow Java bean format CORRECTLY. Here is an example

CustomView class

publicclassCustomViewextendsLinearLayout {
    ...
    private OnCustomViewListener onCustomViewListener;

    ...
    publicvoidsetOnCustomViewListener(OnCustomViewListener onCustomViewListener) {
        this.onCustomViewListener = onCustomViewListener;
    }


    ....
    publicinterfaceOnCustomViewListener {
        voidonCustomViewListenerMethod(int aNumber);
    }
}

XML

<...CustomView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:onCustomViewListener="@{viewModel.viewModelListenerMethod}" // oruse can use app:onCustomViewListener="@{viewModel::viewModelListenerMethod}"
    />

ViewModel

publicclassViewModelextendsBaseObservable{

    publicvoidviewModelListenerMethod(int aNumber){
       // handle listener here
    }
}

Post a Comment for "Data Bindings With Custom Listeners On Custom View"