Get Binding From View Class
Solution 1:
You must bind the inflated view to create the data binding. In your example, you're binding the container of the layout.
You can do this in several ways. The easiest is to bind it as part of inflation:
publicclassCustomViewextendsLinearLayout
{
CustomViewBinding mBinding;
publicCustomView(Context inContext, AttributeSet inAttrs)
{
super(inContext, inAttrs);
LayoutInflaterinflater= LayoutInflater.from(inContext);
// I assume you want it inflated into this ViewGroup
mBinding = CustomViewBinding.inflate(inflater, this, true);
}
publicvoidsetVariable(CustomView inCustomView, VariableType inMyVariable) {
mBinding.setVariable(inMyVariable);
}
...
}
You don't really need a binding adapter unless you don't want the setter as part of your custom view. In that case, you'll still need a way to get the binding, so you'll need to add something like this:
public CustomViewBinding getBinding() { return mBinding; }
so that your binding adapter works.
If you know that the LinearLayout contents are all going to be from the inflated view, you can use a binding adapter like this:
@BindingAdapter({"app:variable"})publicstaticvoidsetVariable(CustomView inCustomView, VariableType inMyVariable)
{
if (inCustomView.getChildCount() == 0) {
return;
}
ViewboundView= inCustomView.getChildAt(0);
CustomViewBindingbinding= DataBindingUtil.getBinding(boundView);
binding.setMyVariable(inMyVariable);
}
If your custom view isn't very custom, you can simply include your layout directly:
<include layout="@layout/custom_view" app:variable="@{myVariableValue}"/>
You would, of course, have to move the LinearLayout into the custom_view.xml.
Solution 2:
Basically, this is how it worked for me:
XML:
<layout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"android:id="@+id/containerView"xmlns:tools="http://schemas.android.com/tools">
.....
</layout>
Java Class:
GeneralOverviewBindingbinding= DataBindingUtil.bind((findViewById(R.id.containerView)));
This basically returns the binding for the given layout root or creates a binding if one does not exist.
Post a Comment for "Get Binding From View Class"