monacotoni monacotoni - 1 year ago 188
Android Question

How can I do for-loops with Android databinding?

Most popular MVVM-frameworks allow some kind of loops for list type properties. For example Knockout has the foreach-binding. It allows you to loop through the elements of the list property and for each element the markup contained in the foreach-loop is duplicated. Inside the copy, the current element is used as the context for data-binding.

I was looking for something similar in Android, but I only saw the possibility to bind a list to a specific ui-element. But this is bad with respect to declarativeness because I need to create a UI element in code.

Is there a way to simulate something similar using the data binding features from Android? If not, is there a workaround? Or a way to extend the binding syntax?

Answer Source

It's not possible as is. The android databinding library uses static XML layout and binds values to attributes. Creating static layout dynamically is not supported and I assume won't ever be. If you want to create a view hierarchy dynamically you still should use views with adapters. That's something you can do with databindings. Just create your own databinding adapter for binding a list to a RecyclerVier. You could bind to a pair of binding:iterator and binding:layout attributes for example and set the RecyclerVier.Adapter inside the databinding adapter.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download