How to change Cursor Color of TextField in Android Jetpack Compose

By Mohammed Rashid •  November 16th, 2022 • 

TextField is one of the most important UI elements of a mobile app. In this short Android Jetpack Compose tutorial, let’s see how to customize the cursor color of a TextField.

Using TextFieldDefaults and textFieldColors you can change the color of the TextField cursor.

@Composable
fun Example() {
    var value by remember { mutableStateOf("") }

    TextField(
        value = value,
        onValueChange = { value = it },
        label = { Text("Enter text") },
        maxLines = 2,
        colors = TextFieldDefaults.textFieldColors(cursorColor = Color.Red),
        modifier = Modifier.padding(20.dp)
    )
}

The cursor color will be changed to red color. See the output given below.

Following is the complete code.

package com.example.myapplication

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.myapplication.ui.theme.MyApplicationTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {
                Surface(
                    color = MaterialTheme.colors.background
                ) {
                    Example()
                }
            }
        }
    }
}

@Composable
fun Example() {
    var value by remember { mutableStateOf("") }

    TextField(
        value = value,
        onValueChange = { value = it },
        label = { Text("Enter text") },
        maxLines = 2,
        colors = TextFieldDefaults.textFieldColors(cursorColor = Color.Red),
        modifier = Modifier.padding(20.dp)
    )
}


@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    MyApplicationTheme {
        Example()
    }
}

That’s how you change the TextField indicator color in Jetpack Compose.

Mohammed Rashid

Keep Reading