Search code examples
androidkotlinmaterial-uiandroid-jetpack-composeandroid-compose-textfield

Label not moving up when focused in BasicTextField


Label not moving up when I focus on the BasicTextField but it's only moving up when I start typing. Here is the BasicTextField I'm using I'm using the same properties of the TextField. Wondering why TextField works like this and BasicTextField which Textfield uses internally doesn't

BasicTextField(
        value = value,
        modifier = Modifier
          .onFocusChanged { isFocused = it.isFocused }
          .focusRequester(focusRequester)
          .background(colors.backgroundColor(enabled).value, shape)
          .indicatorLine(enabled, isError, interactionSource, colors)
          .defaultMinSize(
            minWidth = TextFieldDefaults.MinWidth,
            minHeight = TextFieldDefaults.MinHeight
          ),
        onValueChange = { newText ->
          if (newText.length <= characterLimit || !isTextLimiterVisible) onValueChange(newText)
        },
        enabled = enabled,
        textStyle = AppTheme.Typography.Body.medium.merge(TextStyle(color = colors.textColor(enabled).value)),
        cursorBrush = SolidColor(colors.cursorColor(isError).value),
        visualTransformation = VisualTransformation.None,
        keyboardActions = KeyboardActions(),
        maxLines = TEXT_FIELD_MAX_LINES,
        decorationBox = @Composable { innerTextField ->
          TextFieldDefaults.TextFieldDecorationBox(
            value = value,
            innerTextField = innerTextField,
            enabled = enabled,
            placeholder = {
              BodySmall(text = placeholder, color = AppTheme.Colors.Surface.onSurfaceVariant)
            },
            label = {
              BodyMedium(
                text = label,
                color = if (enabled) {
                  AppTheme.Colors.Surface.onSurfaceVariant
                } else {
                  AppTheme.Colors.Surface.onSurface.level3()
                },
                modifier = Modifier.graphicsLayer {
                  transformOrigin = TransformOrigin(LABEL_SCALE_ORIGIN_X, LABEL_SCALE_ORIGIN_Y)
                  scaleX = labelScale
                  scaleY = labelScale
                }
              )
            },
            singleLine = false,
            isError = isError,
            visualTransformation = VisualTransformation.None,
            interactionSource = interactionSource,
            colors = colors,
          )

Basically using the same implementation as TextField


Solution

  • You have to add the same interactionSource to the BasicTextField

    BasicTextField(
        //...
        interactionSource = interactionSource,
        decorationBox = @Composable { innerTextField ->
            TextFieldDefaults.TextFieldDecorationBox(
                //...
                interactionSource = interactionSource,
            )
        }
    )