Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jetpack Compose how to remove EditText/TextField underline and keep cursor?

Hi I need to remove the underline in my TextField because it look ugly when the TextField is circular. I have sat the activeColor to transparent, but then the cursor wont show (because it's transparent). How can I remove the underline/activeColor and keep the cursor?

enter image description here

Here is my Circular TextField code:

@Composable
fun SearchBar(value: String) {
    // we are creating a variable for
    // getting a value of our text field.
    val inputvalue = remember { mutableStateOf(TextFieldValue()) }

    TextField(
            // below line is used to get
            // value of text field,
            value = inputvalue.value,

            // below line is used to get value in text field
            // on value change in text field.
            onValueChange = { inputvalue.value = it },

            // below line is used to add placeholder
            // for our text field.
            placeholder = { Text(text = "Firmanavn") },

            // modifier is use to add padding
            // to our text field, and a circular border
            modifier = Modifier.padding(all = 16.dp).fillMaxWidth().border(1.dp, Color.LightGray, CircleShape),

            shape = CircleShape,


            // keyboard options is used to modify
            // the keyboard for text field.
            keyboardOptions = KeyboardOptions(
                    // below line is use for capitalization
                    // inside our text field.
                    capitalization = KeyboardCapitalization.None,

                    // below line is to enable auto
                    // correct in our keyboard.
                    autoCorrect = true,

                    // below line is used to specify our
                    // type of keyboard such as text, number, phone.
                    keyboardType = KeyboardType.Text,
            ),

            // below line is use to specify
            // styling for our text field value.
            textStyle = TextStyle(color = Color.Black,
                    // below line is used to add font
                    // size for our text field
                    fontSize = TextUnit.Companion.Sp(value = 15),

                    // below line is use to change font family.
                    fontFamily = FontFamily.SansSerif),

            // below line is use to give
            // max lines for our text field.
            maxLines = 1,

            // active color is use to change
            // color when text field is focused.
            activeColor = Color.Gray,

            // single line boolean is use to avoid
            // textfield entering in multiple lines.
            singleLine = true,

            // inactive color is use to change
            // color when text field is not focused.
            inactiveColor = Color.Transparent,

            backgroundColor = colorResource(id = R.color.white_light),

                    // trailing icons is use to add
                    // icon to the end of tet field.
            trailingIcon = {
                Icon(Icons.Filled.Search, tint = colorResource(id = R.color.purple_700))
            },
    )
like image 495
Christer Avatar asked Jan 18 '21 19:01

Christer


People also ask

What is mutableStateOf in Jetpack Compose?

mutableStateOf creates an observable MutableState<T> , which is an observable type integrated with the compose runtime. interface MutableState<T> : State<T> { override var value: T. } Any changes to value will schedule recomposition of any composable functions that read value .

What is LazyColumn in Jetpack Compose?

A LazyColumn is a vertically scrolling list that only composes and lays out the currently visible items. It's similar to a Recyclerview in the classic Android View system.

How to align Text in Jetpack Compose?

If you want to set manually the text alignment of a Text composable, prefer using TextAlign. Start and TextAlign. End instead of TextAlign. Left and TextAlign.


2 Answers

You can define these attributes to apply a Transparent color:

  • focusedIndicatorColor
  • unfocusedIndicatorColor
  • disabledIndicatorColor

Something like:

   TextField(
       //..
       colors = TextFieldDefaults.textFieldColors(
            textColor = Color.Gray,
            disabledTextColor = Color.Transparent,
            backgroundColor = Color.White,
            focusedIndicatorColor = Color.Transparent,
            unfocusedIndicatorColor = Color.Transparent,
            disabledIndicatorColor = Color.Transparent
        )
    )

enter image description here


Starting with 1.2.0 you can also use the new OutlinedTextFieldDecorationBox together with BasicTextField customizing the border or the indicator line.

    val interactionSource = remember { MutableInteractionSource() }
    val enabled = true
    val singleLine = true
    val colors = TextFieldDefaults.outlinedTextFieldColors()

    BasicTextField(
        value = value,
        onValueChange = onValueChange,
        modifier = modifier,
        // internal implementation of the BasicTextField will dispatch focus events
        interactionSource = interactionSource,
        enabled = enabled,
        singleLine = singleLine
    ) {
        TextFieldDefaults.OutlinedTextFieldDecorationBox(
            value = value,
            visualTransformation = VisualTransformation.None,
            innerTextField = it,
            // same interaction source as the one passed to BasicTextField to read focus state
            // for text field styling
            interactionSource = interactionSource,
            enabled = enabled,
            singleLine = singleLine,
            // update border thickness and shape
            border = {
                TextFieldDefaults.BorderBox(
                    enabled = enabled,
                    isError = false,
                    colors = colors,
                    interactionSource = interactionSource,
                    shape = CircleShape,
                    unfocusedBorderThickness = 1.dp,
                    focusedBorderThickness = 1.dp
                )
            }
        )
    }

enter image description here

Also you can use a TextFieldDecorationBox applying the indicatorLine modifier specifying the focusedIndicatorLineThickness and unfocusedIndicatorLineThickness values:

   val colors = TextFieldDefaults.textFieldColors(
        backgroundColor = White,
        focusedIndicatorColor = Gray)

    BasicTextField(
        modifier = Modifier
            .border(1.dp, Color.LightGray, CircleShape)
            .indicatorLine(
                enabled = enabled,
                isError = false,
                colors = colors,
                interactionSource = interactionSource,
                focusedIndicatorLineThickness = 0.dp,
                unfocusedIndicatorLineThickness = 0.dp
            )
            .background(colors.backgroundColor(enabled).value, CircleShape),
    ) {
        TextFieldDecorationBox(
            //...
            colors = colors
        )
    }
like image 130
Gabriele Mariotti Avatar answered Oct 22 '22 01:10

Gabriele Mariotti


If you don't need TextField parameters / functions like collapsing label, placeholder, etc. you can use a layer of Text / BasicTextField to create a SearchField (which is a suggested workaround according to issue FilledTextField: can't remove bottom indicator ):

@Composable
fun Search(
        hint: String,
        endIcon: ImageVector? = Icons.Default.Cancel,
        onValueChanged: (String) -> Unit,
) {
    var textValue by remember { mutableStateOf(TextFieldValue()) }

    Surface(
        shape = RoundedCornerShape(50),
        color = searchFieldColor
    ) {
        Box(
            modifier = Modifier
                .preferredHeight(40.dp)
                .padding(start = 16.dp, end = 12.dp),
            contentAlignment = Alignment.CenterStart
        )
        {
            if (textValue.text.isEmpty()) {
                Text(
                    text = "Search...",
                    style = MaterialTheme.typography.body1.copy(color = MaterialTheme.colors.onSurface.copy(ContentAlpha.medium)),
                    )
            }

            Row(
                verticalAlignment = Alignment.CenterVertically
            ) {
                BasicTextField(
                    modifier = Modifier.weight(1f),
                    value = textValue,
                    onValueChange = { textValue = it; onValueChanged(textValue.text) },
                    singleLine = true,
                    cursorColor = YourColor,
                )
                endIcon?.let {
                    AnimatedVisibility(
                        visible = textValue.text.isNotEmpty(),
                        enter = fadeIn(),
                        exit = fadeOut()
                    ) {
                        Image(
                            modifier = Modifier
                                .preferredSize(24.dp)
                                .clickable(
                                    onClick = { textValue = TextFieldValue() },
                                    indication = null
                                ),
                            imageVector = endIcon,
                            colorFilter = iconColor
                        )
                    }
                }
            }
        }
    }
}
like image 44
jns Avatar answered Oct 22 '22 00:10

jns