18. LazyColum 条目的增加和删除

315 阅读1分钟

01. Compose 可组合组件之Row And Column

02. Compose 可组合组件之 属性 modifier

03. Compose 可组合组件之Card 图片

04. Compose 字体

05. Compose State

06. Compose SnackBar

07. Compose List

08. Compose ConstrainLayout

09. Compose Button

10. Compose CheckBox

11. Compose 对于复杂界面的尝试

12. Compose 之原生xml布局加入Compose代码

13. Compose 之Compose代码插入xml布局

14. Compose 之简易朋友圈列表

15. Compose 使用CameraX

16. Compose 权限申请Permission

17. Compose 时钟Clock的绘制

18. LazyColum 条目的增加和删除


data class Item(
    var item: String,
    var isNew: Boolean,
)

@Composable
fun Item() {

    val context = LocalContext.current
    val list = mutableStateListOf<Item>()

    repeat(20) {
        list.add(Item(item = "Item $it", isNew = false))
    }

    Column(modifier = Modifier
        .fillMaxSize()
        .padding(start = 10.dp, end = 10.dp)) {
        Button(modifier = Modifier
            .fillMaxWidth()
            .padding(top = 10.dp), onClick = {

            val index = (0..5).random()
            if (index < list.size) {
                list.add(index, Item(item = "insert Item ${(0..5).random()}", isNew = true))
            } else {
                list.add(0, Item(item = "insert Item ${(0..5).random()}", isNew = true))
            }

        }) {
            Text(text = "add Item")
        }

        Button(modifier = Modifier
            .fillMaxWidth()
            .padding(top = 10.dp), onClick = {
            val index = (0..5).random()
            if (index < list.size) {
                list.removeAt(index)
            } else {
                Toast.makeText(context, "无此条目", Toast.LENGTH_SHORT).show()
            }
        }) {
            Text(text = "remove Item")
        }

        LazyColumn(content = {
            items(count = list.size, itemContent = { index ->
                Box(modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 10.dp, bottom = 10.dp)
                    .background(color = if (list[index].isNew) Color.LightGray else Color.DarkGray)) {
                    Text(modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 10.dp, bottom = 10.dp), fontWeight = FontWeight.Medium, fontSize = 20.sp, color = Color.White, textAlign = TextAlign.Center, text = list[index].item)
                }
            })
        })
    }
}