After watching the io16 session, I finally found a solution:
First, create a class with any method annotated as a BindingAdapter .
public class OptionBindingAdapter { private boolean mOptionsShowing; @BindingAdapter("android:text") public void setOption(TextView button, String text) { if (text == null) { return; } if (button.getTranslationY() > 0) { button.setText(text); button.setVisibility(View.VISIBLE); button.animate() .translationY(0) .start(); } else { button.animate() .translationY(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, button.getResources().getDisplayMetrics())) .start(); } } }
Then create a class that implements the DataBindingComponent , there you simply create a getter method that returns an instance of the class above.
public class OptionBindingComponent implements DataBindingComponent { private OptionBindingAdapter mOptionBindingAdapter = new OptionBindingAdapter(); public OptionBindingAdapter getOptionBindingAdapter() { return mOptionBindingAdapter; } }
Now you can create any instance of this component and use it when binding, for example, in Activity # onCreate.
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main, new OptionBindingComponent()); mViewModel = new OptionsViewModel(new OptionsRepository(), this); mBinding.setVariable(me.zhanghailin.androiddatabindingwithanimations.BR.options, mViewModel); }
Done! what it is, the effect is that the binding adapter will be used for this binding instead of the default component.
source share