1

I have some content with textfields passed as a lambda to another composable. Lambda is always a part of layout as it's in both branches of if statement, however when condition of 'if' changes - text fields lose focus. Is there any way to prevent it while keeping current structure?

versions: compose = "2024.06.00" compose-compiler = "1.5.14"

Real use case: two complex container layouts for tablet/mobile that accept main content as lambda. Containers switched based of screen size.

Simplified example:

                    val condition = remember { mutableStateOf(false) }
                    val content = @Composable {
                        TextField(value = "", onValueChange = {})
                    }

                    LaunchedEffect(Unit) {
                        while (isActive) {
                            delay(1000)
                            condition.value = !condition.value
                        }
                    }

                    Column {
                        if (condition.value) {
                            content()
                        } else {
                            content()
                        }
                    }

1 Answer 1

1

Although content is the same in both branches of the if, for the Compose runtime they are two different, unrelated composables. When one has the focus and the condition changes so the other is displayed instead, the other doesn't automatically inherits the focus from the first.

If the content would have an internal state (like a remembered mutableStateOf), that would also be different. You should restructure your code so that content is only called once, then the TextField would keep the focus state.

Sign up to request clarification or add additional context in comments.

2 Comments

I was hoping there exists a workaround or event intended way to achieve desired behaviour without restructuring the code, since it'll result in very cumbersome layout. In case nothing more helpful arises, I'll accept this as an answer
When you call a Composable two times they will always be separate and independent, there is no way around. Although you probably need to restructure your code, I do not think that that ineveitably leads to more complicated code. If you have difficulties with finding a clean solution you can ask about that on the sister site Code Review. They have a different focus there, so make sure you read their How to ask page first. Most importantly, the code you post there already needs to work as intended, it's all about optimizing the code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.