Generate Random Color - Android Studio - Compose

Generate random color(s) using Android Studio and Jetpack Compose

There may be some situations in which you need the feature to generate a random color.  For example, in a list of items, if you want to assign different colors to each item/row, you may have seen the WhatsApp Group Chat List, where each person's name is displayed in a different color. 

I'll do it using a button click. You can do it according to your requirements/needs.

Code

Code Snippet

val generatedColor = Color(
                        Random.nextInt(256),
                        Random.nextInt(256),
                        Random.nextInt(256)
                    )

Full Example

MainActivity.kt

package com.technifysoft.myapplication

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.technifysoft.myapplication.ui.theme.MyApplicationTheme
import kotlin.random.Random


/**
 * MainActivityCompose is the main activity of the application, responsible for setting up the UI.
 */
class MainActivityCompose : ComponentActivity() {
    /**
     * Called when the activity is first created. This is where you should do all of your normal static set up:
     * create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's
     * previously frozen state, if there was one.
     */
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {

                Scaffold(
                    modifier = Modifier.fillMaxSize(),
                ) { innerPadding ->
                    MainUI(innerPadding)
                }

            }
        }
    }
}

@Composable
fun MainUI(innerPadding: PaddingValues) {
    // Get the current context
    val context = LocalContext.current
    // State for background color
    var generatedColor by remember { mutableStateOf(Color(0xFF959595)) }

    Box(
        modifier = Modifier.fillMaxSize()
    ) {
        Column(
            modifier = Modifier.fillMaxSize(),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // Title
            Text(
                text = "Random Color Generator",
                style = MaterialTheme.typography.headlineMedium,
                modifier = Modifier.padding(top = 10.dp)
            )

            Spacer(modifier = Modifier.weight(1f))

            // Color box: Show random generated color
            Box(
                modifier = Modifier
                    .size(250.dp)
                    .background(generatedColor)
            )

            Spacer(modifier = Modifier.weight(1f))

            // Button: click to generate random color
            Button(
                onClick = {
                    //Generate Random Color
                    generatedColor = Color(
                        Random.nextInt(256),
                        Random.nextInt(256),
                        Random.nextInt(256)
                    )
                },
                modifier = Modifier
                    .padding(10.dp)
                    .fillMaxWidth()
                    .height(60.dp),
                shape = RoundedCornerShape(8.dp)
            ) {
                Text("Generate Random Color")
            }
        }
    }

}

/**
 * GreetingPreview is a composable function for previewing the MainUI in Android Studio.
 * It is annotated with @Preview to enable live preview.
 *
 */
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    MyApplicationTheme {
        MainUI(PaddingValues())
    }
}

Screenshots

Generate Random Color - Android Studio - ComposeGenerate Random Color - Android Studio - Compose




Comments

Popular posts from this blog

Picture In Picture | Android Studio | Kotlin

Manage External Storage Permission | Android Studio | Kotlin

How to add AIDL folder | Android Studio