微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 Jetpack Compose 在单击按钮时动态添加视图

如何解决使用 Jetpack Compose 在单击按钮时动态添加视图

每次用户单击“添加”按钮时,我都想动态地将文本字段添加到我的布局中。添加的文本字段应添加在“添加”按钮上方。即步骤 1 文本字段和添加按钮之间。如何通过 Jetpack Compose 实现?下面是屏幕截图,后面是我当前的代码..

enter image description here

代码-

Column(modifier = Modifier.padding(16.dp)) {

            OutlinedTextField(
                modifier = Modifier.fillMaxWidth(),value = step1,onValueChange = {
                    viewmodel.onStep1Changed(it)
                },label = {
                    Text(text = "Step 1...")
                },shape = RoundedCornerShape(8.dp),colors = TextFieldDefaults.textFieldColors(
                    backgroundColor = Color.Transparent),trailingIcon = {
                    Icon(
                        modifier = Modifier.padding(start=10.dp),imageVector = Icons.Filled.Image,tint= Color.Blue,contentDescription = "Select Image"
                    )
                }
            )
            Spacer(modifier = Modifier.height(16.dp))
            Button(onClick = {
             //Todo Dynamically add text fields
            }){
                Text("Add")
            }

        }

解决方法

Column(modifier = Modifier.padding(16.dp)) {
val textFieldCount by remember { mutableStateOf (1) }
            repeat(textFieldCount) {
                OutlinedTextField(
                modifier = Modifier.fillMaxWidth(),value = step1,onValueChange = {
                    viewModel.onStep1Changed(it)
                },label = {
                    Text(text = "Step 1...")
                },shape = RoundedCornerShape(8.dp),colors = TextFieldDefaults.textFieldColors(
                    backgroundColor = Color.Transparent),trailingIcon = {
                    Icon(
                        modifier = Modifier.padding(start=10.dp),imageVector = Icons.Filled.Image,tint= Color.Blue,contentDescription = "Select Image"
                    )
                }
            )
            Spacer(modifier = Modifier.height(16.dp))
        }
            Button(onClick = {
             textFieldCount++
            }){
                Text("Add")
            }

        }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。