How do I bind a List of custom items to a ListView or a RecyclerView? Using only Android DEFAULT DataBinding (no external library)
<layout>
<data>
<import type="java.util.List"/>
<variable name="listOfString" type="List<String>"/>
</data>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:?????="@{listOfString}/> <!--Like we have ItemsSource in WPF-->
</layout>
I came from WPF background, in which there is a ItemTemplate option. Using ItemTemplate you can map data to your view purely through XML. Something like:
<ListView ItemsSource="{Binding Path=UserCollection}">
<ListView.ItemTemplate>
<!--Populate template with each user data-->
<DataTemplate>
<WrapPanel>
<!--Bind to user.Name-->
<TextBlock Text="{Binding Name}" FontWeight="Bold" />
<TextBlock Text="{Binding Age}" FontWeight="Bold" />
<TextBlock Text="{Binding Mail}" />
</WrapPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Data binding can also mean that if an outer representation of the data in an element changes, then the underlying data can be automatically updated to reflect the change. For example, if the user edits the value in a TextBox element, the underlying data value is automatically updated to reflect that change.
One-way binding is a relatively simple type of data binding. Changes to the data provider update automatically in the data consumer data set, but not the other way around. Two-way binding is where changes to either the data provider or the data consumer automatically updates the other.
View binding doesn't support layout variables or layout expressions, so it can't be used to declare dynamic UI content straight from XML layout files. View binding doesn't support two-way data binding.
In Android, the Data Binding Library is a support library that allows you to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically.
If this can help someone, sounds to me that what you are looking for are Binding adadpters from DataBinding feature.
More info can be found here: https://developer.android.com/topic/libraries/data-binding/binding-adapters
This will allow you to define custom property that can be used inside xml and pass a list of items that you need.
@BindingAdapter("nameOfProperty")
public static void loadImage(ListView listView, List listOfString) {
// do the actual logic here
}
This can then be used in xml like app:nameOfPropery="@{listOfString}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With