Search code examples
androidandroid-jetpackandroid-jetpack-composeandroid-compose-textfieldandroid-compose-button

Dynamically add views on click of Button using Jetpack Compose


I want to dynamically add Text Fields to my layout everytime user click "Add" button.Added Text Field should be added above "Add" button .i.e.between Step 1 TextField and Add Button.How can this be achieved through Jetpack Compose?Below is screenshot followed by my current code..

enter image description here

Code-

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

        }

Solution

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