我是 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 )
}
我也对任何更好的方法感兴趣。