How to add Gradient Text Color to TextField in Jetpack Compose

By Mohammed Rashid •  November 16th, 2022 • 

If you are developing a fancy app with some cool styles then you may want to apply gradient colors to different UI elements. In this Jetpack Compose tutorial, we are learning how to give gradient color to TextField.

Brush API helps to create a variety of color gradients in compose. Before proceeding, please remind that using Brush in TextStyle is still experimental.

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.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.ExperimentalTextApi
import androidx.compose.ui.text.TextStyle
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()
                }
            }
        }
    }
}

@OptIn(ExperimentalTextApi::class)
@Composable
fun Example() {
    var value by remember { mutableStateOf("") }

    TextField(
        value = value,
        onValueChange = { value = it },
        textStyle = TextStyle(brush = Brush.linearGradient(
            colors = listOf(Color.Magenta, Color.Cyan)
        )),
        maxLines = 2,
        modifier = Modifier.padding(20.dp)
    )
}


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

The gradient color appears when the user types in a text through the TextField. See the following output of this example.

I hope this Jetpack Compose tutorial is helpful for you.

Mohammed Rashid

Keep Reading