How does DataBindingComponents work based on layout?

Android DataBinding Library is a charming library for learning MVVM. Now the problem is how to play the animation before updating the text in the user interface, based on each layout . (Not a solution for global layouts using the BindingAdapter using a static binding adapter.)

From IO16 video, I know that maybe I can use a DataBindingComponent to achieve this effect, like the setImageUrl example, but I canโ€™t find the sample codes on how exactly the DataBindingComponents and BindingAdapter methods handled by annotated instances work , can anyone elaborate on this?

== update 2016-07-06 ==

I know that I can use a static binding adapter with a custom tag, but that is not what I want.

== update 2017-08-04 == I donโ€™t know why this question is marked as a duplicate, another question is completely different if you know about data binding to androids. I just donโ€™t know how to remove the duplication mark, so do the editing here.

+1
source share
1 answer

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.

+3
source

Source: https://habr.com/ru/post/1236753/


All Articles