Jetpack Compose TextField cuts text on scroll

Viewed 209

I have a TextField with a fixed height. When the user enters a longer text it will scroll. It will cut off any text within the padding when scrolling:

enter image description here

Basically something like this:

var text by remember { mutableStateOf("") }
TextField(
    value = text,
    onValueChange = { value -> text = value },
    modifier = modifier
        .fillMaxWidth()
        .height(100.dp),
    colors = TextFieldDefaults.textFieldColors(
        focusedIndicatorColor = Color.Transparent,
        unfocusedIndicatorColor = Color.Transparent,
        backgroundColor = Color.Transparent
    )
)

It is possible to adjust/remove the padding for a TextField, by using BasicTextField directly, e.g. see this stack overflow question.

However I want to keep the padding, but without the clipping of the text when the user scrolls. A simple Text Composable has this behavior.

2 Answers

You can use BasicTextField and modify its decorationBox parameter. Simply put innerTextField() inside a scrollable Column and add Spacers at the top and the bottom of it.

var text by remember {
        mutableStateOf("Hello Stackoverflow")
    }
    val paddingSize = remember { 16.dp }

    BasicTextField(
        modifier = Modifier
            .height(100.dp),
        value = text,
        onValueChange = { text = it },
        decorationBox = { innerTextField ->
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .verticalScroll(state = rememberScrollState())
            ) {
                Spacer(modifier = Modifier.height(paddingSize))
                innerTextField()
                Spacer(modifier = Modifier.height(paddingSize))
            }

        }
    )

Just use the maxLines parameter of the TextField to avoid clipping. Set it to 1 or 2, per your case, then adjust the height/font-size so the max lines you specify are accomodated correctly. It will likely start to snap to the visible portion, cutting the extra stuff entirely.

Related