|

How to Change Surface Background Color in Android Jetpack Compose

Android Jetpack Compose is a modern, fully declarative UI toolkit that is designed to make it easier for developers to create beautiful and effective user interfaces. One of the common tasks when developing an Android application is setting the background color of a Surface.

In this blog post, we will walk you through how to change Surface background color in Jetpack Compose.

To change the background color of a Surface, you simply need to set the color attribute inside the Surface composable function. Here is an example:

@Composable
fun SurfaceExample() {
    Surface(
        modifier = Modifier.padding(16.dp).fillMaxSize(),
        color = Color.LightGray
    ) {
        Text(
            text = "Hello, Jetpack Compose!",
            modifier = Modifier.padding(16.dp)
        )
    }
}

In this example, the background color of the Surface is set to light gray.

jetpack compose surface background color

Following is the complete code for reference.

package com.example.example

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
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.example.ui.theme.ExampleTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            ExampleTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    SurfaceExample()
                }
            }
        }
    }
}

@Composable
fun SurfaceExample() {
    Surface(
        modifier = Modifier.padding(16.dp).fillMaxSize(),
        color = Color.LightGray
    ) {
        Text(
            text = "Hello, Jetpack Compose!",
            modifier = Modifier.padding(16.dp)
        )
    }
}

@Preview(showBackground = true)
@Composable
fun ExamplePreview() {
    ExampleTheme {
        SurfaceExample()
    }
}

Changing the background color of a Surface in Jetpack Compose is straightforward. This guide should give you a solid foundation for creating and customizing Surfaces in your Jetpack Compose application.

Similar Posts

Leave a Reply