Search code examples
androidxamllistviewandroid-listviewitemtemplate

Composite list items in ListView in Android


I am trying to define a composite list item in an Android ListView but it seems to be overly complex. (By this I mean where I compose each item in the listview from multiple views/controls)

In Xaml this is very simple and clean. Yes, I know undfortunately Android does not support binding but I am looking for the best way to accomplish this in Android.

XAML example:

<ListBox ItemsSource="{Binding Days}" x:Name="DataList">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding DateString}" x:Name="DateBox" />
                <TextBlock Text="{Binding Name}" x:Name="NameBox"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

If you know Xaml, then there is no code to make the binding work other then setting the VM as the DataContext and exposing the bound items as public properties.

As far as I can tell, there is a lot of work to make this happen in Android. I need to create a custom ListAdapter, lots of wiring and overriding, etc. Is there a better way to do this?

Can someone please point me to docs/tutorial that demonstrates the best practices for solving this problem in Android.

Thanks!


Solution

  • In this case, yes there's more code to write than if you had done it in WPF. The equivalent of defining a DataTemplate on an ItemsControl in WPF is making a custom Adapter and implementing the getView method.

    The World of ListView video is a must watch for understanding best practices with Adapters.

    http://www.youtube.com/watch?v=wDBM6wVEO70