Here's my code for a form text field composable:
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FormTextFieldComponent(
topText: String,
initialText: String=""
) = Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
// Small Text at the top (dynamic content)
var textState by remember { mutableStateOf(TextFieldValue(initialText)) }
OutlinedTextField(
value = textState,
onValueChange = {
textState = it
},
label = { Text(topText) }
)
}
However, it shows up only once with this code (only shows the first textfield):
FormTextFieldComponent("First Name", "Van")
Spacer(modifier = Modifier.height(1.dp))
FormTextFieldComponent("Last Name", "Chen")
Spacer(modifier = Modifier.height(1.dp))
What is wrong?
The quick answer is:
You are using fillMaxSize()
, so when the first TextField is render, it fills all the screen, then the second one is rendering outside the screen.
So you should use fillMaxWidth()
instead of fillMaxSize()
Column(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
)
You can prove this using this code, wrapping one of the TextFields and scaling the 0.5 of the full size
@Composable
fun Greeting(modifier: Modifier = Modifier) {
val scrollState = rememberScrollState()
Column(
modifier = modifier.fillMaxSize()
) {
Box(modifier = Modifier.fillMaxSize(0.5f)){
FormTextFieldComponent(topText = "First Name", initialText = "Van")
}
Spacer(modifier = Modifier.height(10.dp))
FormTextFieldComponent(topText = "Last Name", initialText = "Chen")
Spacer(modifier = Modifier.height(1.dp))
}
}
Also as recommendation to have more control in the sizes, try to always put a modifier
parameter to composable functions like this:
@Composable
fun FormTextFieldComponent(
modifier: Modifier = Modifier,
topText: String,
initialText: String=""
) {
Column(
modifier = modifier
.fillMaxWidth()
.padding(16.dp)
){ }
}
Is a good practice in order to modify this from the parent.