如何使用 pojo class 而不是列表来初始化适配器?

How to initialize adapter with pojo class instead of list?

您好,我正在学习使用 kotlin 的新 android 喷气背包。在使用带绑定的 recyclerview 时,我们需要使用空列表初始化适配器,大多数时候我看到人们将列表传递给适配器。但是如何使用嵌套的 pojo class 而不是列表来做同样的事情呢?

这是数据样本

{"results":[{"gender":"female","name":{"title":"Ms","first":"Ines","last":"Hernandez"},"location":{"street":{"number":1495,"name":"Calle de Alcalá"},"city":"Málaga","state":"Melilla","country":"Spain","postcode":86664,"coordinates":{"latitude":"-17.4716","longitude":"106.6687"},"timezone":{"offset":"-5:00","description":"Eastern Time (US & Canada), Bogota, Lima"}},"email":"ines.hernandez@example.com","login":{"uuid":"66c3248d-d257-45b1-bd9c-3ebcba6e7b7a","username":"smallduck939","password":"maxxxx","salt":"kxEtQgmY","md5":"14e95cbbda70d692f74c5073a21b6a1e","sha1":"bf12732af070dd38e6418b31260ba10f74f14e94","sha256":"7f1b6be17c0bf339d6153c7c4379fd0d8564bf0cfa2f9e6ae9caef2a037f7e0a"},"dob":{"date":"1982-04-07T17:51:39.317Z","age":39},"registered":{"date":"2016-02-20T17:10:42.682Z","age":5},"phone":"964-947-469","cell":"677-793-075","id":{"name":"DNI","value":"96170049-S"},"picture":{"large":"https://randomuser.me/api/portraits/women/66.jpg","medium":"https://randomuser.me/api/portraits/med/women/66.jpg","thumbnail":"https://randomuser.me/api/portraits/thumb/women/66.jpg"},"nat":"ES"}]}

这是我的数据classes

data class UserResponse(val results:ArrayList<User>?)

以及后续的,所以你可以看到我已经从“结果”键开始了起点。

现在在声明适配器时我需要传递一个列表,例如

 private val listAdapter = UserAdapter(arrayListOf())

然后声明类似

//from another project

private val ListDataObserver = Observer<List<Animal>> {list-> list?.let { binding.animalList.visibility=View.VISIBLE
listAdapter.updateanimalList(it)}}

但是您可以在现有数据中看到数据是 Single<> 类型,即以键开头,那么在这种情况下我该如何初始化 recyclerview

private val listAdapter = UserAdapter(arrayListOf())

因为数据 class 不是列表类型?我应该直接从这里解析吗?

[{"gender":"female","name":{"title":"Ms","first":"Ines","last":"Hernande

请帮助我解决这个问题,因为我无法初始化 recyclerview 并随后使用 observable。 谢谢:)

你必须将相同的列表传递给你从观察者那里得到的适配器对象,见下面的代码

private val listAdapter = UserAdapter(arrayListOf<Animal>())

private val ListDataObserver = Observer< UserResponse> {userRes-> userRes?.let { binding.animalList.visibility=View.VISIBLE listAdapter.updateanimalList(it.result)}}

注意:Animal 是您从 UserResponse 对象中的观察者那里获得的列表