Android Data Binding Library vs Kotlin Android Extensions

后端 未结 3 1597
故里飘歌
故里飘歌 2021-01-31 14:37

I\'m reading about how the MVVM architecture works and how to use Android Data Binding Library help.

In a very general way I understand that Android Data Binding creates

3条回答
  •  失恋的感觉
    2021-01-31 14:57

    Kotlin Android Extensions does not stand for only view binding. It contains other features as well. But I guess you’re talking about the view binding/caching features of Kotlin Android Extensions and wonder whether we still need data binding, since we already got rid of the findViewById calls with the synthetic properties of Kotlin. That was the question I asked to myself and my conclusion is, yes, data binding is still worth using.

    From official documentation:

    The Data Binding Library creates an immutable field in the binding class for each view that has an ID in the layout… The library extracts the views including the IDs from the view hierarchy in a single pass. This mechanism can be faster than calling the findViewById() method for every view in the layout.

    So data binding doesn’t call findViewById on views one by one. Kotlin’s synthetic classes, on the other hand, still calls findViewById on the views under the hood, but it calls it only once for each view and caches the view reference for next calls. (Here is an article about it)

    Besides, data binding has more to offer than only view caching. You can use data tags for passing data to the binding implementation and declare them in your xml, instead of setting them programmatically. This way you can get rid of the boilerplate code that you use for populating data, like those "setText"s, "setImageResource"s etc. You can set event listeners from xml using data binding. You can also come up with your own attributes using custom binding adapters. When used to its whole power, it can significantly reduce your Java/Kotlin code.

    Edit: It seems that Google Android team recommends against use of kotlin synthetic properties. This article summarizes the discussion around this issue. And you can see in the new Udacity course prepared by Google that they use data binding as recommended practice.

    Edit2: If you don't like the idea of "putting business logic in your xml", if you are not interested in setting or getting data from xml, if you simply want to avoid use of findViewByIds in a safe and efficient manner, than you can go with ViewDataBinding library instead. It is a simplified version of data binding library. It doesn't let you set data from your xml but it binds your views in a safe and efficient manner.

提交回复
热议问题