Async 和 RecyclerView 在获取数据时显示列表

问题描述 投票:0回答:1

我是 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 )
}

我也对任何更好的方法感兴趣。

android kotlin wear-os
1个回答
0
投票

不清楚您是在获取分页数据还是完整数据,但您需要的是在适配器中使用

flow
和 Diff 回调,即
PagingDataAdapter
(example) 或
ListAdatper
(example)。

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

© www.soinside.com 2019 - 2024. All rights reserved.