androidtextviewandroid-jetpack-compose

How to increase space inside Text Field in compose


I am using a text field with a size constraint, The text that I am typing in does not go to the very end, it seems there is padding. When I use trailing icons then it gets worse, trailing icons take half of the text field space.

How can I make the text align to the edges, and the trailing icon to the right?

    fun TextField(
    value: String,
    onValueChange: (String) -> Unit,
    label: String
) {
    var textFieldValue by remember { mutableStateOf(TextFieldValue(value)) }
    OutlinedTextField(
        modifier = Modifier
            .width(100.dp)
            .height(60.dp),
        value = textFieldValue,
        onValueChange = {
            textFieldValue = it
            onValueChange(it.text)
        },
        textStyle = LocalTextStyle.current.copy(
            textAlign = TextAlign.Left
        ),
        label = { Text(label, fontSize = 12.sp) },
        singleLine = true,
        trailingIcon = {
            // Add a trailing icon that clears the text field when clicked
            if (textFieldValue.text.trim().isNotEmpty()) {
                IconButton(
                    modifier = Modifier
                        .size(20.dp)
                        .padding(end = 1.dp) .background(Color.Yellow)
                    , onClick = {
                        textFieldValue = TextFieldValue(" ")
                        onValueChange("")
                    }) {
                    Icon(Icons.Filled.Clear, contentDescription = "Clear")
                }
            }
        }
    )
}

Solution

  • I pasted your code in Android Studio and inspected the results. First, be careful with naming your Composable as "TextField", there is danger of confusing it with the official TextField. Better name it as "MyTextField".

    With trailingIcon displayed, I get the following padding:

    enter image description here

    There is no unusual padding there. Android in general enforces a certain touch target size of at least 48x48dp to ensure accessibility. You should not attempt to override this.

    However when you want to show or hide the trailingIcon depending on a condition, you must ensure to do it the right way, otherwise the space will be reserved even though there is no IconButton shown at all.

    Make sure to pass in the Composable to the trailingIcon if the condition is met, otherwise set it to null, then the space is freed.

    trailingIcon =  if (someCondition) {
        // Add a trailing icon that clears the text field when clicked
        {
            IconButton(
                //...
            ) {
                Icon(Icons.Filled.Clear, contentDescription = "Clear")
            }
        }
    } else {
        null  // If set to null, the space will be availabe for text
    }
    

    enter image description here

    I hope this clarifies it for you!