先看看效果, 这是一个国家的区号数据, 进行分组显示, 服务端下载的是乱序的区号数据

引入依赖

洪洋的万能 adapter

1
2
implementation 'com.zhy:base-rvadapter:3.0.3'
implementation 'com.github.promeg:tinypinyin:2.0.3'

处理数据

服务端返回的数据格式

1
2
3
4
5
6
7
8
9
{
"code": "+93",
"name": "阿富汗",
"name_en": "Afghanistan"
}, {
"code": "+355",
"name": "阿尔巴尼亚",
"name_en": "Albania"
}

然后bean

1
2
3
4
5
6
7
8
9
10
data class CodeResp(
@SerializedName("total") var total: Int = 0,
@SerializedName("items") var items: List<CodeItem> = listOf()
)

data class CodeItem(
@SerializedName("code") var code: String = "",
@SerializedName("name") var name: String = "",
@SerializedName("name_en") var nameEn: String = ""
) : BaseBean()

下面就是排序了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
val ob = object : BaseObserver<HttpResult<CodeResp>>(this) {
override fun _onNext(t: HttpResult<CodeResp>) {
t.data?.let {
datas.clear()
//处理分组数据
val map = hashMapOf<String, ArrayList<CodeItem>>()
it.items.forEachIndexed { _, codeItem ->
//名称转拼音, 并获取首字母, 并且放到map里面
val char = Pinyin.toPinyin(codeItem.name, "").substring(0, 1)
if (!map.containsKey(char)) {
map[char] = arrayListOf(codeItem)
} else {
map[char]!!.add(codeItem)
}
}
//对map的key进行排序
val sortKeys = map.keys.sorted()
//遍历排序后的数组, 分别从map中获取list
sortKeys.forEach {
datas.add(TitleBean(it))
datas.addAll(map[it]!!)
}

list.adapter.notifyDataSetChanged()
val defaultCode = getCurrentCountryCode()
datas.forEachIndexed { index, baseBean ->
if (baseBean is CodeItem && baseBean.code == defaultCode){
list.scrollToPosition(index)
}
}
}
}

override fun onSubscribe(d: Disposable) {
super.onSubscribe(d)
d.addTo(compositeDisposable)
show(getString(R.string.get_data_from_server))
}
}

区块链安卓开发群:区块链安卓开发 431969409