How to change Background Color of TextField in Android Jetpack Compose

By Mohammed Rashid •  November 22nd, 2022 • 

TextField is one of the most used UI components in mobile app design. Thus, styling TextField with appropriate colors is very important. Let’s learn how to change the background color of TextField in Jetpack Compose.

TextField has a gray color background by default. You may want to change it most of the time.

textfield background jetpack compose

You can customize the TextField colors using the TextFieldColors interface. Thus you can change the default background color with the help of TextFieldDefaults.textFieldColors. See the code snippet given below.

@Composable
fun TextFieldExample() {
    var value by remember { mutableStateOf("") }
    TextField(
        value = value,
        onValueChange = {
            value = it
        },
        colors = TextFieldDefaults.textFieldColors(backgroundColor = Color.Cyan),
        label = { Text("Enter text") },
        modifier = Modifier.padding(20.dp)
    )
}

You will get the following output of a TextField with a cyan background.

Following is the complete code for reference.

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
                ) {
                    TextFieldExample()
                }
            }
        }
    }
}

@Composable
fun TextFieldExample() {
    var value by remember { mutableStateOf("") }
    TextField(
        value = value,
        onValueChange = {
            value = it
        },
        colors = TextFieldDefaults.textFieldColors(backgroundColor = Color.Cyan),
        label = { Text("Enter text") },
        modifier = Modifier.padding(20.dp)
    )
}


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

I hope you like this Jetpack Compose TextField background color example.

Mohammed Rashid

Keep Reading