Skip to main content

android kotlin - Palette API Example

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.graphics.Bitmap
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.appcompat.app.AppCompatActivity
import com.cfsuman.kotlintutorials.databinding.ActivityMainBinding


class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // Get the bitmap from assets
        val bitmap:Bitmap? = assetsBitmap("flower103.jpg")

        // Display the bitmap in image view
        binding.imageView.setImageBitmap(bitmap)

        // Button click listener
        binding.button.setOnClickListener{

            // If bitmap is not null then do the next task
            bitmap?.apply {
                // Get the palette colors
                val list =this.Colors

                // Get the palette color names
                val names = mutableListOf<String>()
                for (i in list){
                    names.add(i.name)
                }

                // Initializing an ArrayAdapter
                val adapter = ArrayAdapter(
                    applicationContext, // Context
                    android.R.layout.simple_spinner_item, // Layout
                    names // Array
                )

                // Set the drop down view resource
                adapter.setDropDownViewResource(
                    android.R.layout.simple_dropdown_item_1line)

                // Finally, data bind the spinner object with adapter
                binding.spinner.adapter = adapter;

                // Set an on item selected listener for spinner object
                binding.spinner.onItemSelectedListener = object: AdapterView
                .OnItemSelectedListener{
                    override fun onItemSelected(
                        parent:AdapterView<*>, view: View,
                        position: Int, id: Long){
                        val item = list[position]

                        binding.textLayout.setBackgroundColor(item.color)

                        binding.tvTitle.text = item.name

                        if (item.swatch!=null){
                            binding.tvTitle.setTextColor(
                                item.swatch.titleTextColor)
                            binding.tvBody.setTextColor(
                                item.swatch.bodyTextColor)
                        }
                    }

                    override fun onNothingSelected(parent: AdapterView<*>){
                        // Another interface callback
                    }
                }
            }
        }
    }
}
PaletteManager.kt

package com.cfsuman.kotlintutorials

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import androidx.palette.graphics.Palette
import java.io.IOException
import java.io.InputStream


// Extension property to get palette colors from bitmap
val Bitmap.Colors:MutableList<PaletteColor>
    get() {
        // Initialize a list of palette color
        val list = mutableListOf<PaletteColor>()

        // Generate the palette from bitmap
        val palette = this.palette

        // Dark muted color and swatch
        val darkMutedColor = palette.getDarkMutedColor(Color.RED)
        val darkMutedSwatch = palette.darkMutedSwatch
        list.add(PaletteColor(
            "Dark muted color",darkMutedColor,darkMutedSwatch)
        )

        // Dark vibrant color and swatch
        val darkVibrantColor = palette.getDarkVibrantColor(Color.MAGENTA)
        val darkVibrantSwatch = palette.darkVibrantSwatch
        list.add(PaletteColor(
            "Dark vibrant color",
            darkVibrantColor,darkVibrantSwatch))

        // Dominant color and swatch
        val dominantColor = palette.getDominantColor(Color.BLUE)
        val dominantSwatch = palette.dominantSwatch
        list.add(PaletteColor("Dominant Color",
            dominantColor,dominantSwatch))

        // Light muted color and swatch
        val lightMutedColor = palette.getLightMutedColor(Color.YELLOW)
        val lightMutedSwatch = palette.lightMutedSwatch
        list.add(PaletteColor("Light muted color",
            lightMutedColor,lightMutedSwatch))

        // Light vibrant color and swatch
        val lightVibrantColor = palette.getLightVibrantColor(Color.CYAN)
        val lightVibrantSwatch = palette.lightVibrantSwatch
        list.add(PaletteColor("Light vibrant color",
            lightVibrantColor,lightVibrantSwatch))

        // Muted color and swatch
        val mutedColor = palette.getMutedColor(Color.GRAY)
        val mutedSwatch = palette.mutedSwatch
        list.add(PaletteColor("Muted color",mutedColor,mutedSwatch))
        return list
    }


// Initialize a data class to hold the palette color and swatch
data class PaletteColor(val name:String,
                        val color:Int, val swatch: Palette.Swatch?)


// Extension property to generate palette from bitmap
val Bitmap.palette: Palette
    get() {
        return Palette.from(this).generate()
    }


// Extension method get bitmap from assets
fun Context.assetsBitmap(path:String): Bitmap?{
    val inputStream: InputStream
    var bitmap: Bitmap? = null
    try {
        inputStream = assets.open(path)
        bitmap = BitmapFactory.decodeStream(inputStream)
    }catch (e: IOException){
        // Handle exception here
    }

    return bitmap
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    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:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="12dp"
    android:background="#F8F8FF">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="175dp"
        android:scaleType="centerCrop"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Generate Palette"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="@+id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/button"
        app:layout_constraintTop_toTopOf="@+id/button" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/textLayout"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/button">

        <TextView
            android:id="@+id/tvTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="8dp"
            android:textSize="24sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/tvBody"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:padding="8dp"
            android:textSize="18sp"
            android:text="Lorem Ipsum is simply dummy text of the
            printing and typesetting industry. Lorem Ipsum has been
            the industry's standard dummy text ever since
            the 1500s, when an unknown printer took a galley
            of type and scrambled it to make a type specimen book.
            It has survived not only five centuries,
            but also the leap into electronic typesetting,
            remaining essentially unchanged."
            app:layout_constraintTop_toBottomOf="@+id/tvTitle"/>

    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
build.gradle [app]

implementation 'androidx.palette:palette:1.0.0'

Popular posts from this blog

Restricting Jetpack Compose TextField to Numeric Input Only

Jetpack Compose has revolutionized Android development with its declarative approach, enabling developers to build modern, responsive UIs more efficiently. Among the many components provided by Compose, TextField is a critical building block for user input. However, ensuring that a TextField accepts only numeric input can pose challenges, especially when considering edge cases like empty fields, invalid characters, or localization nuances. In this blog post, we'll explore how to restrict a Jetpack Compose TextField to numeric input only, discussing both basic and advanced implementations. Why Restricting Input Matters Restricting user input to numeric values is a common requirement in apps dealing with forms, payment entries, age verifications, or any data where only numbers are valid. Properly validating input at the UI level enhances user experience, reduces backend validation overhead, and minimizes errors during data processing. Compose provides the flexibility to implement ...

jetpack compose - TextField remove underline

Compose TextField Remove Underline The TextField is the text input widget of android jetpack compose library. TextField is an equivalent widget of the android view system’s EditText widget. TextField is used to enter and modify text. The following jetpack compose tutorial will demonstrate to us how we can remove (actually hide) the underline from a TextField widget in an android application. We have to apply a simple trick to remove (hide) the underline from the TextField. The TextField constructor’s ‘colors’ argument allows us to set or change colors for TextField’s various components such as text color, cursor color, label color, error color, background color, focused and unfocused indicator color, etc. Jetpack developers can pass a TextFieldDefaults.textFieldColors() function with arguments value for the TextField ‘colors’ argument. There are many arguments for this ‘TextFieldDefaults.textFieldColors()’function such as textColor, disabledTextColor, backgroundColor, cursorC...

jetpack compose - Image clickable

Compose Image Clickable The Image widget allows android developers to display an image object to the app user interface using the jetpack compose library. Android app developers can show image objects to the Image widget from various sources such as painter resources, vector resources, bitmap, etc. Image is a very essential component of the jetpack compose library. Android app developers can change many properties of an Image widget by its modifiers such as size, shape, etc. We also can specify the Image object scaling algorithm, content description, etc. But how can we set a click event to an Image widget in a jetpack compose application? There is no built-in property/parameter/argument to set up an onClick event directly to the Image widget. This android application development tutorial will demonstrate to us how we can add a click event to the Image widget and make it clickable. Click event of a widget allow app users to execute a task such as showing a toast message by cli...