【问题标题】:Async and RecyclerView to display list while fetching dataAsync 和 RecyclerView 在获取数据时显示列表
【发布时间】:2021-10-01 09:10:09
【问题描述】:

我是 Android 新手

我在 RecyclerView 中显示列表项时遇到问题。 我希望一个一个显示列表并在它仍在加载时追加。

但是发生的情况是,在获取所有项目后会出现列表。

这是我的片段

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_lock_list, container, false)
        val recyclerView = view.findViewById<RecyclerView>(R.id.list)

        for(device in devices) {
            fetchBuildingAddress(device)
        }

        if (recyclerView is RecyclerView) {
            with(recyclerView) {
                layoutManager = LinearLayoutManager(context)
                adapter = deviceRecyclerViewAdapter
            }
        }

        return view
    }


    private fun fetchBuildingAddress(device: Device) {
        deviceWearableService.getBuilding(device.buildingId) {
            when(it) {
                is DeviceWearableServiceImpl.State.Success -> {
                    val buildingName = it.resources.buildingAddress.address1

                    val deviceBuilding = DeviceBuillding(device, buildingName)
                    deviceRecyclerViewAdapter.insertDevice(deviceBuilding)
                }
            else -> {
                    // TODO: ERROR STATE
                }
            }

        }

    }

在我的insertDevice 我只是在适配器中调用notifyItemInserted

fun insertDevice(updateDeviceBuilding: DeviceBuillding) {
    deviceBuilding.add(updateDeviceBuilding)
    notifyItemInserted(deviceBuilding.size - 1 )
}

您还可以提出更好的行为建议!非常感谢您。

【问题讨论】:

  • 这可能是因为deviceWearableService.getBuilding 因为您在循环中一个接一个地调用它而没有任何延迟,因此所有项目可能会在几毫秒的差异内一次加载。加载一次需要多长时间? deviceWearableService.getBuilding 到底是什么?执行时间是固定的还是随机的?
  • 您好!你可能是对的,因为它只获取建筑细节。它是一个 API。我想知道应该如何处理。

标签: android kotlin wear-os


【解决方案1】:

不清楚您是在获取分页数据还是完整数据,但您需要在适配器中使用 flow 和 Diff 回调,即 PagingDataAdapter(example) 或 ListAdatper(example) .

它的实现很简单,你可以在网上找到它。

【讨论】:

  • 非常感谢!会试试这个。但这不是分页数据:(我所做的只是拆分收到的内容。
猜你喜欢
  • 2020-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-15
  • 1970-01-01
  • 2015-05-03
  • 2019-05-18
  • 1970-01-01
相关资源
最近更新 更多