首页 > 解决方案 > 如何使用 TAdapterBindSource 刷新 TListView LiveBinding

问题描述

我正在使用 Delphi 10.3.1 (Firemonkey FMX) 来构建 android 和 iOS 应用程序。我有一个 TListView,与 AdapterBindSource 进行实时绑定。我的问题是:Adapter refreshed 后没有出现新记录

===============

  1. 我创建了一个 TObjectList,向其中添加了 3 个对象
  2. 我通过传递一个 TObjectList 来创建一个 TBindSourceAdapter 来创建它。
  3. 我将 TBindSourceAdapter 分配给 AdapterBindSource1.Adapter。
  4. 然后我释放TObjectList并重新创建它,添加4个新创建的对象(其中3个是旧记录,修改了一些数据,1个是新记录)
  5. 我做 TBindSourceAdapter.Refresh 和 TAdapterBindSource.Refresh
  6. 这 3 条旧记录刷新成功,显示修改数据,但新记录在 Android 和 iOS 中未显示
  7. 相同的逻辑在 Windows 平台上运行良好

===============

我的逻辑

创建 TObjectList

首先我从 Rest Server 获取记录并转换为 TObjectList

TData : class(TObject) ... // a class stored some data
TDataList = class(TObjectList<TData>)
// then I get data from Rest Server and created FList, it is a Form private variable
FList := TDataList.Create; // a private Form variable
// create Tdata objects and add to FList .....

创建 TBindSourceAdapter,分配给 AdapterBindSource

    var ABindSourceAdapter: TBindSourceAdapter;
// ....
    ABindSourceAdapter := TListBindSourceAdapter<TData>.Create(self, FList, True);
    AdapterBindSource1.Adapter := ABindSourceAdapter;
    AdapterBindSource1.Active := true;

然后记录显示在 ListView 与 AdapterBindSource 的实时绑定

刷新 FList 记录

当单击刷新按钮时,我触发再次从 Rest 服务器获取数据,我释放 FList 并重新创建它

FreeAndNil(FList);
FList := TDataList.Create; // re-create the list, then create Tdata object and add to it again.

刷新适配器

然后我刷新适配器

    AdapterBindSource1.Adapter.Refresh;
    AdapterBindSource1.Refresh;

这里3条旧记录刷新成功,修改后的数据显示正确,但是没有显示新记录,TListView仍然只显示3条记录。

笔记:

  1. 刷新过程中我没有重新创建 TListBindSourceAdapter 并再次分配给 AdapterBindSource1.Adapter,记录仍然刷新成功。
  2. 但是,即使我重新创建 TListBindSourceAdapter 并再次分配给 AdapterBindSource1.Adapter,新记录仍然没有出现,只会导致内存泄漏。

我该如何解决这个问题?有没有我想刷新 TListView 的东西?还是我的 BindSourceAdapter 刷新逻辑错误?

谢谢你的帮助。

标签: delphifiremonkey

解决方案


我找到了刷新 TListView 的解决方案。

该问题是由于在此处重新创建 TObjectList 而发生的:

FreeAndNil(FList);
FList := TDataList.Create; // re-create the list, then create Tdata object and add to it again.

释放列表并重新创建导致问题。我将其更改为清除列表并向其中添加新对象。

FList.Clear();
// then add objects to it again, such as FList.AddRange(...)

然后 AdapterBindSource 刷新成功。

如果 TObjectList 空闲并重新创建,则适配器不再正确使用它。


推荐阅读