Android Kotlin: How to create GradientDrawable Programmatically

Introduction

This code demonstrates creating and applying GradientDrawable programmatically in an Android app written in Kotlin. GradientDrawable allows you to define visual effects with color transitions within a specific shape. This approach offers more flexibility compared to defining gradients in the layout XML file.

Breakdown

The code consists of two parts: the MainActivity class and the layout file activity_main.xml.

  • MainActivity.kt:

    • This class defines the activity's behavior. The onCreate method sets up the UI and applies gradients to three ImageViews.
    • Three separate methods (linearGradientDrawable, radialGradientDrawable, and sweepGradientDrawable) are used to create different gradient types. Each method:
      • Creates a GradientDrawable object using the apply block for concise configuration.
      • Sets the color array using colors property with color codes parsed using Color.parseColor.
      • Defines the gradient type using gradientType (e.g., GradientDrawable.LINEAR_GRADIENT).
      • Sets the shape using shape (always GradientDrawable.RECTANGLE in this example).
      • Optionally sets additional properties like orientation (GradientDrawable.Orientation.BOTTOM_TOP) for linear gradient and gradientRadius for radial gradient.
      • Applies a common border around the drawable using setStroke.
    • Finally, each method sets the programmatically created drawable as the background for a corresponding ImageView using setImageDrawable.
  • activity_main.xml:

    • This file defines the layout of the activity using ConstraintLayout.
    • It contains three ImageViews (imageView, imageView2, and imageView3) for displaying the gradients.
    • Additionally, there are TextViews (textView, textView2, and textView3) to label each gradient type.

Summary

This code provides a practical example of creating linear, radial, and sweep gradients programmatically in Kotlin for an Android application. The separation of gradient creation logic into dedicated methods improves code organization and reusability.


MainActivity.kt

package com.example.jetpack

import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // set image view drawable liner gradient
        imageView.setImageDrawable(linearGradientDrawable())

        // set image view drawable radial gradient
        imageView2.setImageDrawable(radialGradientDrawable())

        // set image view drawable sweep gradient
        imageView3.setImageDrawable(sweepGradientDrawable())
    }
}


// method to generate linear gradient drawable
private fun linearGradientDrawable():GradientDrawable{
    return GradientDrawable().apply {
        colors = intArrayOf(
            Color.parseColor("#008000"),
            Color.parseColor("#8DB600"),
            Color.parseColor("#D0FF14")
        )
        gradientType = GradientDrawable.LINEAR_GRADIENT
        shape = GradientDrawable.RECTANGLE
        orientation = GradientDrawable.Orientation.BOTTOM_TOP

        // border around drawable
        setStroke(5,Color.parseColor("#4B5320"))
    }
}


// method to generate radial gradient drawable
private fun radialGradientDrawable():GradientDrawable{
    return GradientDrawable().apply {
        colors = intArrayOf(
            Color.parseColor("#DA1884"),
            Color.parseColor("#FFF600"),
            Color.parseColor("#800020")
        )
        gradientType = GradientDrawable.RADIAL_GRADIENT
        shape = GradientDrawable.RECTANGLE

        gradientRadius = 350F

        // border around drawable
        setStroke(5,Color.parseColor("#CD5700"))
    }
}


// method to generate sweep gradient drawable
private fun sweepGradientDrawable():GradientDrawable{
    return GradientDrawable().apply {
        colors = intArrayOf(
            Color.parseColor("#00BFFF"),
            Color.parseColor("#00CC99"),
            Color.parseColor("#D70040"),
            Color.parseColor("#F7E7CE"),
            Color.parseColor("#DFFF00")
        )
        gradientType = GradientDrawable.SWEEP_GRADIENT
        shape = GradientDrawable.RECTANGLE

        // border around drawable
        setStroke(5,Color.parseColor("#232B2B"))
    }
}
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/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="150dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:srcCompat="@tools:sample/avatars" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Linear Gradient"
        app:layout_constraintEnd_toEndOf="@+id/imageView"
        app:layout_constraintStart_toStartOf="@+id/imageView"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="0dp"
        android:layout_height="150dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        tools:srcCompat="@tools:sample/avatars" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Radial Gradient"
        app:layout_constraintEnd_toEndOf="@+id/imageView2"
        app:layout_constraintStart_toStartOf="@+id/imageView2"
        app:layout_constraintTop_toBottomOf="@+id/imageView2" />

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="0dp"
        android:layout_height="150dp"
        android:layout_marginStart="16dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2"
        tools:srcCompat="@tools:sample/avatars" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Sweep Gradient"
        app:layout_constraintEnd_toEndOf="@+id/imageView3"
        app:layout_constraintStart_toStartOf="@+id/imageView3"
        app:layout_constraintTop_toBottomOf="@+id/imageView3" />

</androidx.constraintlayout.widget.ConstraintLayout>
More android kotlin tutorials