数据绑定自定义项列表

13

如何将自定义项目列表绑定到ListView或RecyclerView?仅使用Android默认的DataBinding(不使用外部库)

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

1
我正在阅读Android数据绑定指南,但我认为这是一个可以在SO上找到的好问题,所以我提出来了。 - rocketspacer
@nmtuan:您能否添加更多关于您使用数据绑定想要实现的具体细节吗? - AndiGeeky
1
@AndiGeeky 我只想让ListView或RecyclerView显示项目集合,可以是任何东西,比如“类Message { String content }”。 - rocketspacer
1
就像在WPF或Windows Forms中,您可以在集合类型控件上使用DataSource或ItemsSource,但我无法在Android上找到类似的属性来进行“绑定”。 - rocketspacer
@nmtuan:你是在谈论自定义设计还是自定义数据? - AndiGeeky
我正在遵循这个指南 https://developer.android.com/topic/libraries/data-binding/index.html - rocketspacer
2个回答

2
如果这能帮到某人,那么我认为你正在寻找的是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
}

这可以在 XML 中使用,例如:app:nameOfPropery="@{listOfString}"

-1

1
他不是在寻找一个库。 - Agna JirKon Rx
1
当然,最好是一遍又一遍地重新发明轮子。你总可以查看源代码并找到有趣的部分。 - Aleksander Mielczarek

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接