数据绑定自定义项的列表



如何将自定义项列表绑定到ListView或RecyclerView?仅使用安卓DEFAULT数据绑定(无外部库)

<layout>
    <data>
        <import type="java.util.List"/>
        <variable name="listOfString" type="List&lt;String>"/>
    </data>
    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:?????="@{listOfString}/>  <!--Like we have ItemsSource in WPF-->
</layout>

我来自WPF背景,其中有一个ItemTemplate选项。使用ItemTemplate,您可以纯粹通过XML将数据映射到视图。类似于:

<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>

如果这能帮助到某人,我觉得你正在寻找的是来自DataBinding功能的绑定适配器。

更多信息可以在这里找到:https://developer.android.com/topic/libraries/data-binding/binding-adapters

这将允许您定义可在xml中使用的自定义属性,并传递所需的项目列表。

@BindingAdapter("nameOfProperty")
public static void loadImage(ListView listView, List listOfString) {
  // do the actual logic here
}

这可以在类似app:nameOfPropery="@{listOfString}" 的xml中使用

查看此库:https://github.com/evant/binding-collection-adapter.

此库允许将自定义对象的ObservableList绑定到RecyclerView。

最新更新