Search code examples
androidkotlinlayoutandroid-jetpackandroid-jetpack-compose

how to measure the height of textField


enter image description here

code:

val focusManager = LocalFocusManager.current
var code by remember { mutableStateOf("") }
var money by remember { mutableStateOf("") }

Column() {
    Row() {
        TextField(
            modifier = Modifier.wrapContentSize(),
            value = code,
            keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.Number,
                imeAction = ImeAction.Done
            ),
            keyboardActions = KeyboardActions(onDone = {
                focusManager.clearFocus()
            }),
            singleLine = true,

            label = { Text("Code") },
            onValueChange = { pscCode ->
                code = pscCode.filter { it.isDigit() }.take(16)
            })
        Button(modifier = Modifier.fillMaxWidth(),
            onClick = {…}
        )
        {
            Text("Save data")
        }
    }
    Row() {
        TextField(
            modifier = Modifier.wrapContentSize(),
            value = money,
            singleLine = true,
            keyboardOptions = KeyboardOptions(
                keyboardType = KeyboardType.Number,
                imeAction = ImeAction.Done
            ),
            keyboardActions = KeyboardActions(onDone = {
                focusManager.clearFocus()
            }),
            label = { Text("Money amount") },
            onValueChange = { moneyAmount ->
                money = moneyAmount
                    .trim()
                    .replace(",", ".")
                    .take(5)
            })

        Button(modifier = Modifier.fillMaxWidth(),
            onClick = {…}
        ) {
            Text("Clean data")
        }
    }
}

I've been trying to match the size of buttons to the size of textFields but I didn't find a way, I tried to measure the height of textBoxes (no results), is there a better (and working) way to fill those gaps? Thanks in advance :)


Solution

  • Use the intrinsic measurements:

       Row(Modifier.height(IntrinsicSize.Min)) {
                TextField( /* your code */)
                Button(
                    modifier = Modifier.fillMaxHeight(),
                    onClick = {}
                )
                {
                    Text("Save")
                }
            }
    

    enter image description here

    As explained in the doc:

    The Row composable's minIntrinsicHeight will be the maximum minIntrinsicHeight of its children. The Button element's minIntrinsicHeight is 0 as it doesn't occupy space if no constraints are given; the TextField minIntrinsicHeight will be that of the text given a specific width. Therefore, the Row element's height constraint will be the max minIntrinsicHeight of the TextField. Button will then expand its height to the height constraint given by the Row.