23 10 月, 2023
By: LiHan
Jetpack Compose – ExpandableList
Compose ExpandableList
Result
DumpData
利用 https://json-generator.com/ 產生資料
[
'{{repeat(100, 100)}}',
{
id: '{{objectId()}}',
name: '{{firstName()}} {{surname()}}',
gender: '{{gender()}}'
}
]
Gson函式庫讀取 json file
Kotlin
// https://mvnrepository.com/artifact/com.google.code.gson/gson
implementation("com.google.code.gson:gson:2.10.1")
建立User Model 將 json File 讀出
Kotlin
data class User(
val id : String,
val name : String,
val gender : String
)
data class UserGroup(
val lastName : String,
val userList : List<User>
){
companion object{
fun getAllUserDataFromJsonData() : Map<Char, List<User>> {
val gson = Gson()
val itemType = object : TypeToken<List<User>>(){}.type
val items : List<User> = gson.fromJson<List<User>?>(
users , itemType).sortedBy{ it.name.first() }
val groupList = items.groupBy {
it.name.first()
}
return groupList
}
}
}
Logic
Kotlin
val isExpandList = remember {
mutableStateListOf<Boolean>().apply {
addAll(List(state.data.keys.size) { false })
}
}
LazyColumn{
state.data.onEachIndexed { index, entry ->
val isExpand = isExpandList[index]
item {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
.clickable {
isExpandList[index] = !isExpand
}
) {
Text(
modifier = Modifier
.weight(1f),
text = entry.key.toString(),
fontWeight = FontWeight.Bold
)
Icon(
imageVector = if (isExpand) Icons.Default.ArrowDropDown else Icons.Default.KeyboardArrowUp,
contentDescription = "expand icon"
)
}
}
if (isExpand){
items(entry.value){
AnimatedVisibility(visible = true,
) {
Row(
modifier = Modifier.fillMaxWidth()
.padding(16.dp),
) {
Text(
text = it.name
)
}
}
}
}
}
}