欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

18. LazyColum 条目的增加和删除

程序员文章站 2022-05-14 20:30:20
...

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)
                }
            })
        })
    }
}