Generate Random Color | Android Studio | Kotlin
Generate random color(s) in Android Studio IDE with Kotlin language
There may have some situations in which you need the feature to generate the random color. For example, in a list of items if you want to give different colors to each item/row or you may have seen the WhatsApp Group Chat List, each person's name is of a different color.
I'll do it using a button click. You can do it according to your requirements/needs.
Video
Coming Soon
Code
Code Snippet
val rnd = Random() val color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256))
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp" tools:context=".MainActivity"> <TextView style="@style/TextAppearance.Material3.HeadlineMedium" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="10dp" android:text="Random Color Generator" /> <View android:id="@+id/generatedColorView" android:layout_width="250dp" android:layout_height="250dp" android:layout_centerInParent="true" android:background="#959595" /> <com.google.android.material.button.MaterialButton android:id="@+id/generateColorBtn" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:minHeight="60dp" android:text="Generate Ranndom Color" app:cornerRadius="8dp" /> </RelativeLayout>
MainActivity.kt
package com.technifysoft.randomcolor import android.graphics.Color import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import com.google.android.material.button.MaterialButton import java.util.* class MainActivity1 : AppCompatActivity() { //UI Views private lateinit var generatedColorView: View private lateinit var generateColorBtn: MaterialButton override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //init UI Views generatedColorView = findViewById(R.id.generatedColorView) generateColorBtn = findViewById(R.id.generateColorBtn) //handle generateColorBtn click, generate random color generateColorBtn.setOnClickListener { //function call to generate random color generateRandomColor() } } private fun generateRandomColor() { //Generate Random Color val rnd = Random() val color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256)) //set the randomly generated color as background color of a UI View. You may use it anywhere you want generatedColorView.setBackgroundColor(color) } }
Comments
Post a Comment