android kotlin - Chip background color

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import android.widget.TextView
import androidx.core.view.children
import com.google.android.material.chip.Chip
import com.google.android.material.chip.ChipGroup


class MainActivity : Activity() {
    private lateinit var chipGroup:ChipGroup
    private lateinit var textView:TextView

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

        // get the widgets reference from XML layout
        chipGroup = findViewById(R.id.chipGroup)
        textView = findViewById(R.id.textView)
        val chipYellow = findViewById<Chip>(R.id.chipYellow)

        // get chip group initially checked chips
        handleSelection()

        // set checked change listener for each chip on chip group
        chipGroup.children.forEach {
            val chip = it as Chip

            chip.setOnCheckedChangeListener { buttonView, isChecked ->
                handleSelection()
            }

            // set chip background color programmatically
            // both for chip checked and unchecked states
            chip.chipBackgroundColor = setChipBackgroundColor(
                checkedColor = Color.parseColor("#8DB600"),
                unCheckedColor = Color.parseColor("#FF9966")
            )
        }
    }


    // function to get chip group checked chips
    private fun handleSelection(){
        textView.text = "Checked Chips : "
        chipGroup.checkedChipIds.forEach{
            textView.append("\n${findViewById<Chip>(it).text}")
        }
    }
}


// function to generate color state list for chip background
fun setChipBackgroundColor(
    checkedColor: Int = Color.GREEN,
    unCheckedColor: Int = Color.RED
): ColorStateList{
    val states = arrayOf(
        intArrayOf(android.R.attr.state_checked),
        intArrayOf(-android.R.attr.state_checked)
    )

    val colors = intArrayOf(
        // chip checked background color
        checkedColor,
        // chip unchecked background color
        unCheckedColor
    )

    return ColorStateList(states, colors)
}
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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DCDCDC"
    android:padding="32dp">

    <com.google.android.material.chip.ChipGroup
        android:id="@+id/chipGroup"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:singleSelection="false"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.chip.Chip
            android:id="@+id/chipRed"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/Widget.MaterialComponents.Chip.Choice"
            android:text="Red" />

        <com.google.android.material.chip.Chip
            android:id="@+id/chipGreen"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/Widget.MaterialComponents.Chip.Entry"
            android:text="Green" />

        <com.google.android.material.chip.Chip
            android:id="@+id/chipYellow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/Widget.MaterialComponents.Chip.Action"
            android:checkable="true"
            android:text="Yellow" />

        <com.google.android.material.chip.Chip
            android:id="@+id/chipBlue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/Widget.MaterialComponents.Chip.Filter"
            android:enabled="false"
            android:text="Blue" />

        <com.google.android.material.chip.Chip
            android:id="@+id/chipBlack"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/Widget.MaterialComponents.Chip.Filter"
            android:text="Black" />

        <com.google.android.material.chip.Chip
            android:id="@+id/chipMagenta"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checkable="true"
            android:text="Magenta" />

    </com.google.android.material.chip.ChipGroup>

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:fontFamily="sans-serif-condensed-medium"
        android:gravity="center"
        android:padding="8dp"
        android:textColor="#4F42B5"
        android:textSize="22sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/chipGroup"
        tools:text="TextView" />

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

android kotlin - Chip checked color programmatically

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import android.widget.TextView
import androidx.core.view.children
import com.google.android.material.chip.Chip
import com.google.android.material.chip.ChipGroup


class MainActivity : Activity() {
    private lateinit var chipGroup:ChipGroup
    private lateinit var textView:TextView

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

        // get the widgets reference from XML layout
        chipGroup = findViewById(R.id.chipGroup)
        textView = findViewById(R.id.textView)

        // get chip group initially checked chips
        handleSelection()

        // set checked change listener for each chip on chip group
        chipGroup.children.forEach {
            val chip = it as Chip

            chip.setOnCheckedChangeListener { buttonView, isChecked ->
                handleSelection()
            }

            // set chip background color programmatically
            // both for chip checked and unchecked states
            chip.chipBackgroundColor = colorStates()
        }
    }


    // function to get chip group checked chips
    private fun handleSelection(){
        textView.text = "Checked Chips : "
        chipGroup.checkedChipIds.forEach{
            val chip = findViewById<Chip>(it)
            textView.append("\n${chip.text}")
        }
    }
}


// function to generate color state list for chip
fun colorStates(): ColorStateList{
    val states = arrayOf(
        intArrayOf(android.R.attr.state_checked),
        intArrayOf(-android.R.attr.state_checked)
    )

    val colors = intArrayOf(
        // chip checked color
        Color.parseColor("#B8860B"),
        // chip unchecked color
        Color.parseColor("#BDB76B")
    )

    return ColorStateList(states, colors)
}
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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DCDCDC"
    android:padding="32dp">

    <com.google.android.material.chip.ChipGroup
        android:id="@+id/chipGroup"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:singleSelection="false"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.chip.Chip
            android:id="@+id/chipRed"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/Widget.MaterialComponents.Chip.Filter"
            android:text="Red" />

        <com.google.android.material.chip.Chip
            android:id="@+id/chipGreen"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/Widget.MaterialComponents.Chip.Filter"
            android:text="Green" />

        <com.google.android.material.chip.Chip
            android:id="@+id/chipYellow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/Widget.MaterialComponents.Chip.Filter"
            android:text="Yellow" />

        <com.google.android.material.chip.Chip
            android:id="@+id/chipBlue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/Widget.MaterialComponents.Chip.Filter"
            android:text="Blue" />

        <com.google.android.material.chip.Chip
            android:id="@+id/chipBlack"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/Widget.MaterialComponents.Chip.Filter"
            android:text="Black" />

        <com.google.android.material.chip.Chip
            android:id="@+id/chipMagenta"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/Widget.MaterialComponents.Chip.Filter"
            android:text="Magenta" />

    </com.google.android.material.chip.ChipGroup>

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:fontFamily="sans-serif-condensed-medium"
        android:gravity="center"
        android:padding="8dp"
        android:textColor="#4F42B5"
        android:textSize="22sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/chipGroup"
        tools:text="TextView" />

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

android kotlin - ChipGroup get selected chips

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import android.widget.TextView
import androidx.core.view.children
import com.google.android.material.chip.Chip
import com.google.android.material.chip.ChipGroup


class MainActivity : Activity() {
    private lateinit var chipGroup:ChipGroup
    private lateinit var textView:TextView

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

        // get the widgets reference from XML layout
        chipGroup = findViewById(R.id.chipGroup)
        textView = findViewById(R.id.textView)

        // get chip group initially checked chips
        handleSelection()

        // set checked change listener for each chip on chip group
        chipGroup.children.forEach {
            (it as Chip).setOnCheckedChangeListener { 
                    buttonView, isChecked ->
                handleSelection()
            }
        }
    }


    // function to get chip group checked chips
    private fun handleSelection(){
        textView.text = "Checked Chips : "
        chipGroup.checkedChipIds.forEach{
            val chip = findViewById<Chip>(it)
            textView.append("\n${chip.text}")
        }
    }
}
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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DCDCDC"
    android:padding="32dp">

    <com.google.android.material.chip.ChipGroup
        android:id="@+id/chipGroup"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:singleSelection="false"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.chip.Chip
            android:id="@+id/chipRed"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/Widget.MaterialComponents.Chip.Filter"
            android:text="Red" />

        <com.google.android.material.chip.Chip
            android:id="@+id/chipGreen"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/Widget.MaterialComponents.Chip.Filter"
            android:checked="true"
            android:text="Green" />

        <com.google.android.material.chip.Chip
            android:id="@+id/chipYellow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/Widget.MaterialComponents.Chip.Filter"
            android:text="Yellow" />

        <com.google.android.material.chip.Chip
            android:id="@+id/chipBlue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/Widget.MaterialComponents.Chip.Filter"
            android:checked="true"
            android:text="Blue" />

        <com.google.android.material.chip.Chip
            android:id="@+id/chipBlack"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/Widget.MaterialComponents.Chip.Filter"
            android:text="Black" />

    </com.google.android.material.chip.ChipGroup>

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:fontFamily="sans-serif-condensed-medium"
        android:gravity="center"
        android:padding="8dp"
        android:textColor="#4F42B5"
        android:textSize="22sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/chipGroup"
        tools:text="TextView" />

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

android kotlin - ChipGroup add chip programmatically

MainActivity.kt

package com.example.jetpack

import android.content.Context
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.chip.Chip
import com.google.android.material.chip.ChipGroup
import kotlinx.android.synthetic.main.activity_main.*


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

        val context = this

        // get chip group initial checked chip text
        val chip: Chip? = findViewById(chipGroup.checkedChipId)
        textView.text = "Checked Chip : ${chip?.text}"


        // set chip group checked change listener
        chipGroup.setOnCheckedChangeListener { group, checkedId ->
            // get the checked chip instance from chip group
            (findViewById<Chip>(checkedId))?.let {
                // Show the checked chip text on text view
                textView.text = "Checked Chip : ${it.text}"
            }
        }


        // add chip to chip group programmatically
        button.setOnClickListener {
            (it as Button).isEnabled = false
            chipGroup.addChip(context,"Magenta")
            chipGroup.addChip(context,"Pink")
            chipGroup.addChip(context,"Black")
        }
    }
}


// create chip programmatically and add it to chip group
fun ChipGroup.addChip(context: Context, label: String){
    Chip(context).apply {
        id = View.generateViewId()
        text = label
        isClickable = true
        isCheckable = true
        isCheckedIconVisible = false
        isFocusable = true
        addView(this)
    }
}
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"
    android:background="#FEFEFA"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="add Chips"
        android:backgroundTint="#E97451"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.chip.ChipGroup
        android:id="@+id/chipGroup"
        style="@style/Widget.MaterialComponents.ChipGroup"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="8dp"
        app:checkedChip="@id/chipGreen"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button"
        app:selectionRequired="true"
        app:singleSelection="true">

        <com.google.android.material.chip.Chip
            android:id="@+id/chipRed"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checkable="true"
            android:text="Red"
            app:checkedIconVisible="false" />

        <com.google.android.material.chip.Chip
            android:id="@+id/chipGreen"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checkable="true"
            android:text="Green"
            app:checkedIconVisible="false" />

        <com.google.android.material.chip.Chip
            android:id="@+id/chipYellow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checkable="true"
            android:text="Yellow"
            app:checkedIconVisible="false" />

    </com.google.android.material.chip.ChipGroup>

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:fontFamily="sans-serif-condensed-medium"
        android:gravity="center"
        android:padding="8dp"
        android:textColor="#4F42B5"
        android:textSize="22sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/chipGroup"
        tools:text="TextView" />

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

android kotlin - ChipGroup single selection

MainActivity.kt

package com.example.jetpack

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.chip.Chip
import kotlinx.android.synthetic.main.activity_main.*


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

        // get chip group initial checked chip text
        val chip: Chip? = findViewById(chipGroup.checkedChipId)
        textView.text = "Checked Chip : ${chip?.text}"


        // set chip group checked change listener
        chipGroup.setOnCheckedChangeListener { group, checkedId ->
            // get the checked chip instance from chip group
            (findViewById<Chip>(checkedId))?.let {
                // Show the checked chip text on text view
                textView.text = "Checked Chip : ${it.text}"
            }
        }
    }
}
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"
    android:background="#FEFEFA"
    tools:context=".MainActivity">

    <com.google.android.material.chip.ChipGroup
        android:id="@+id/chipGroup"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="32dp"
        android:layout_marginEnd="8dp"
        app:singleSelection="true"
        app:selectionRequired="true"
        app:checkedChip="@id/chipGreen"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.chip.Chip
            android:id="@+id/chipRed"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/Widget.MaterialComponents.Chip.Choice"
            android:text="Red" />

        <com.google.android.material.chip.Chip
            android:id="@+id/chipGreen"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/Widget.MaterialComponents.Chip.Choice"
            android:text="Green" />

        <com.google.android.material.chip.Chip
            android:id="@+id/chipYellow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/Widget.MaterialComponents.Chip.Choice"
            android:text="Yellow" />

        <com.google.android.material.chip.Chip
            android:id="@+id/chipBlue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/Widget.MaterialComponents.Chip.Choice"
            android:text="Blue" />

        <com.google.android.material.chip.Chip
            android:id="@+id/chipBlack"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/Widget.MaterialComponents.Chip.Choice"
            android:text="Black" />

    </com.google.android.material.chip.ChipGroup>

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:fontFamily="sans-serif-condensed-medium"
        android:gravity="center"
        android:padding="8dp"
        android:textColor="#4F42B5"
        android:textSize="22sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/chipGroup"
        tools:text="TextView" />

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

android kotlin - NumberPicker string values

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.os.Bundle
import android.widget.NumberPicker
import android.widget.TextView


class MainActivity : Activity() {
    private lateinit var numberPicker:NumberPicker
    private lateinit var textView:TextView

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

        // get the widgets reference from XML layout
        numberPicker = findViewById(R.id.numberPicker)
        textView = findViewById(R.id.textView)

        // display string values to the number picker
        // at first, initialize a new array instance with string values
        val colors = arrayOf("Royal purple", "Sapphire", "Sandy brown",
            "Black olive", "Android green", "Pink lace", "Barbie Pink")

        // set the number picker minimum and maximum values
        numberPicker.minValue = 0
        numberPicker.maxValue = colors.size - 1

        // set the valued to be displayed in number picker
        numberPicker.displayedValues = colors

        // get number picker selected value
        textView.text = "Selected Color : ${colors[numberPicker.value]}"

        // number picker value change listener
        numberPicker.setOnValueChangedListener { picker, oldVal, newVal ->
            // display the picker current selected value to text view
            textView.text = "Selected Color : ${colors[newVal]}"
        }
    }
}
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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DCDCDC"
    android:padding="32dp">

    <NumberPicker
        android:id="@+id/numberPicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:descendantFocusability="blocksDescendants"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:fontFamily="sans-serif-condensed-medium"
        android:gravity="center"
        android:padding="8dp"
        android:textColor="#4F42B5"
        android:textSize="22sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/numberPicker"
        tools:text="TextView" />

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

android kotlin - NumberPicker divider height

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.res.Resources
import android.os.Bundle
import android.widget.NumberPicker


class MainActivity : Activity() {
    private lateinit var numberPicker:NumberPicker

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

        // get the widgets reference from XML layout
        numberPicker = findViewById(R.id.numberPicker)

        // display string values to the number picker
        // at first, initialize a new array instance with string values
        val colors = arrayOf("Red", "Green", "Blue", "Yellow",
            "Magenta", "Black", "Pink")

        // set the number picker minimum and maximum values
        numberPicker.minValue = 0
        numberPicker.maxValue = colors.size - 1

        // set the valued to be displayed in number picker
        numberPicker.displayedValues = colors

        // set number picker divider height in pixels
        // for api level 29 and up
        if (android.os.Build.VERSION.SDK_INT >=
            android.os.Build.VERSION_CODES.Q) {
            // set divider height in pixels
            numberPicker.selectionDividerHeight = 20
        }else{
            numberPicker.setDividerHeight(20)
        }
    }
}


// set number picker divider height in pixels for api level up to 28
fun NumberPicker.setDividerHeight(height: Int) {
    val pickerFields = NumberPicker::class.java.declaredFields
    for (pf in pickerFields) {
        if (pf.name == "mSelectionDividerHeight") {
            pf.isAccessible = true
            try {
                // set divider height in pixels
                pf.set(this, height)
            } catch (e: java.lang.IllegalArgumentException) {
                // log exception here
            } catch (e: Resources.NotFoundException) {
                // log exception here
            } catch (e: IllegalAccessException) {
                // log exception here
            }
            break
        }
    }
}
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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DCDCDC"
    android:padding="32dp">

    <NumberPicker
        android:id="@+id/numberPicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:descendantFocusability="blocksDescendants"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

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

android kotlin - NumberPicker remove divider

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.res.Resources
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.widget.NumberPicker


class MainActivity : Activity() {
    private lateinit var numberPicker:NumberPicker

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

        // get the widgets reference from XML layout
        numberPicker = findViewById(R.id.numberPicker)

        // display string values to the number picker
        // at first, initialize a new array instance with string values
        val colors = arrayOf("Red", "Green", "Blue", "Yellow",
            "Magenta", "Black", "Pink")

        // set the number picker minimum and maximum values
        numberPicker.minValue = 0
        numberPicker.maxValue = colors.size - 1

        // set the valued to be displayed in number picker
        numberPicker.displayedValues = colors

        // remove number picker divider for api level up to 28
        if (android.os.Build.VERSION.SDK_INT <
            android.os.Build.VERSION_CODES.Q) {
            numberPicker.removeDivider()
        }
    }
}


// extension function to remove number picker divider
// for api level up to 28
fun NumberPicker.removeDivider() {
    val pickerFields = NumberPicker::class.java.declaredFields
    for (pf in pickerFields) {
        if (pf.name == "mSelectionDivider") {
            pf.isAccessible = true
            try {
                val colorDrawable = ColorDrawable(Color.TRANSPARENT)
                pf[this] = colorDrawable
            } catch (e: java.lang.IllegalArgumentException) {
                // log exception here
            } catch (e: Resources.NotFoundException) {
                // log exception here
            } catch (e: IllegalAccessException) {
                // log exception here
            }
            break
        }
    }
}
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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DCDCDC"
    android:padding="32dp">

    <!--
        NumberPicker divider color for api level 29 and up
        set number picker divider color to transparent to remove it
        android:theme="@style/NumberPickerTheme"
    -->
    <NumberPicker
        android:id="@+id/numberPicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:descendantFocusability="blocksDescendants"
        android:theme="@style/NumberPickerTheme"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
res/values/styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.MaterialComponents.Light">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="NumberPickerTheme" parent="AppTheme">
        <!-- Set NumberPicker divider color transparent to remove divider -->
        <item name="colorControlNormal">#00FFFFFF</item>
    </style>

</resources>
More android kotlin tutorials

android kotlin - NumberPicker divider color

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.content.res.Resources
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.widget.NumberPicker


class MainActivity : Activity() {
    private lateinit var numberPicker:NumberPicker

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

        // get the widgets reference from XML layout
        numberPicker = findViewById(R.id.numberPicker)

        // set number picker minimum and maximum value
        numberPicker.minValue = 0
        numberPicker.maxValue = 10

        // set number picker divider color for api level up to 28
        if (android.os.Build.VERSION.SDK_INT <
            android.os.Build.VERSION_CODES.Q) {
            numberPicker.setDividerColor(Color.RED)
        }
    }
}


// extension function to set number picker
// divider color for api level up to 28
fun NumberPicker.setDividerColor(color: Int) {
    val pickerFields = NumberPicker::class.java.declaredFields
    for (pf in pickerFields) {
        if (pf.name == "mSelectionDivider") {
            pf.isAccessible = true
            try {
                val colorDrawable = ColorDrawable(color)
                pf[this] = colorDrawable
            } catch (e: java.lang.IllegalArgumentException) {
                e.printStackTrace()
            } catch (e: Resources.NotFoundException) {
                e.printStackTrace()
            } catch (e: IllegalAccessException) {
                e.printStackTrace()
            }
            break
        }
    }
}
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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DCDCDC"
    android:padding="32dp">

    <!--
        NumberPicker divider color for api level 29 and up
        android:theme="@style/NumberPickerTheme"
    -->
    <NumberPicker
        android:id="@+id/numberPicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:descendantFocusability="blocksDescendants"
        android:theme="@style/NumberPickerTheme"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
res/values/styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.MaterialComponents.Light">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>


    <style name="NumberPickerTheme" parent="AppTheme">
        <!-- NumberPicker divider color -->
        <item name="colorControlNormal">#ff0000</item>
    </style>

</resources>
More android kotlin tutorials

android kotlin - NumberPicker text size

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.graphics.Paint
import android.os.Bundle
import android.util.TypedValue
import android.widget.EditText
import android.widget.NumberPicker


class MainActivity : Activity() {
    private lateinit var numberPicker:NumberPicker

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

        // get the context
        val context = this
        val textSize = 50F

        // get the widgets reference from XML layout
        numberPicker = findViewById(R.id.numberPicker)

        // set number picker minimum and maximum value
        numberPicker.minValue = 0
        numberPicker.maxValue = 10

        // set number picker text size to 50 sp or equivalent pixels
        if (android.os.Build.VERSION.SDK_INT >=
            android.os.Build.VERSION_CODES.Q) {
            // float: the text size in pixel units
            numberPicker.textSize = textSize.spToPixels(context)
        }else{
            numberPicker.changeTextSize(context,textSize)
        }
    }
}


// extension function to set number picker text size
@SuppressLint("SoonBlockedPrivateApi")
fun NumberPicker.changeTextSize(context: Context, textSize: Float) {
    try {
        val selectorWheelPaintField = javaClass
            .getDeclaredField("mSelectorWheelPaint")
        selectorWheelPaintField.isAccessible = true
        (selectorWheelPaintField[this] as Paint)
            .textSize = textSize.spToPixels(context)

    } catch (e: NoSuchFieldException) {
        // log exception here
    } catch (e: IllegalAccessException) {
        // log exception here
    } catch (e: IllegalArgumentException) {
        // log exception here
    }

    val count = childCount
    for (i in 0 until count) {
        val child = getChildAt(i)
        if (child is EditText) child
            .setTextSize(TypedValue.COMPLEX_UNIT_SP,textSize)
    }
    invalidate()
}


// extension function to convert sp to equivalent pixels
fun Float.spToPixels(context: Context): Float{
    return TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_SP,
        this,
        context.resources.displayMetrics
    )
}
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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DCDCDC"
    android:padding="32dp">

    <NumberPicker
        android:id="@+id/numberPicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:descendantFocusability="blocksDescendants"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

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

android kotlin - NumberPicker text color

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.annotation.SuppressLint
import android.app.Activity
import android.graphics.Color
import android.graphics.Paint
import android.os.Bundle
import android.util.Log
import android.widget.EditText
import android.widget.NumberPicker


class MainActivity : Activity() {
    private lateinit var numberPicker:NumberPicker

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

        // get the widgets reference from XML layout
        numberPicker = findViewById(R.id.numberPicker)

        // set number picker minimum and maximum value
        numberPicker.minValue = 0
        numberPicker.maxValue = 10

        // set number picker text color to red
        if (android.os.Build.VERSION.SDK_INT >=
            android.os.Build.VERSION_CODES.Q) {
            numberPicker.textColor = Color.RED
        }else{
            numberPicker.changeTextColor(Color.RED)
        }
    }
}


// extension function to set number picker text color
@SuppressLint("SoonBlockedPrivateApi")
fun NumberPicker.changeTextColor(color: Int) {
    try {
        val selectorWheelPaintField = javaClass
            .getDeclaredField("mSelectorWheelPaint")
        selectorWheelPaintField.isAccessible = true
        (selectorWheelPaintField[this] as Paint).color = color
    } catch (e: NoSuchFieldException) {
        Log.d("exception", e.message.toString())
    } catch (e: IllegalAccessException) {
        Log.d("exception", e.message.toString())
    } catch (e: IllegalArgumentException) {
        Log.d("exception", e.message.toString())
    }
    val count = childCount
    for (i in 0 until count) {
        val child = getChildAt(i)
        if (child is EditText) child.setTextColor(color)
    }
    invalidate()
}
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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DCDCDC"
    android:padding="32dp">

    <NumberPicker
        android:id="@+id/numberPicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:descendantFocusability="blocksDescendants"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

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

android kotlin - Disable soft keyboard on NumberPicker

Disabling Soft Keyboard on NumberPicker in Android with Kotlin

This code demonstrates how to programmatically prevent the soft keyboard from appearing when a user interacts with a specific NumberPicker in an Android application written in Kotlin.

The code defines a MainActivity class that extends the Activity class. Inside onCreate(), it inflates the layout file activity_main.xml and retrieves references to two NumberPicker widgets using findViewById.

NumberPicker 1 - Setting Numeric Values:

The first NumberPicker is configured with numeric values. It sets the minimum value to 0 and the maximum value to 20.

NumberPicker 2 - Setting String Values and Disabling Soft Keyboard:

The second NumberPicker showcases a more complex setup. An array named colors is created containing string values representing colors. The NumberPicker's minimum and maximum values are set based on the array size. Finally, the displayedValues property is assigned the colors array to display these string values on the picker.

Crucially, the line numberPicker2.descendantFocusability = NumberPicker.FOCUS_BLOCK_DESCENDANTS disables the soft keyboard for this specific NumberPicker. This leverages the descendantFocusability property of NumberPicker and sets it to a constant value FOCUS_BLOCK_DESCENDANTS. This instructs the system to prevent any of the NumberPicker's descendants (including the edit text used for manual input) from receiving focus, effectively stopping the soft keyboard from appearing when the user interacts with this NumberPicker.

The provided activity_main.xml file defines the layout for the activity. It includes two NumberPicker widgets with appropriate constraints within a ConstraintLayout. Interestingly, it also includes a commented-out line setting android:descendantFocusability="blocksDescendants" on the first NumberPicker in the XML itself. This approach achieves the same outcome as the code in onCreate but demonstrates an alternative way to disable the soft keyboard through layout attributes.

Summary

This code snippet provides two methods for disabling the soft keyboard on a NumberPicker in Android with Kotlin. The first approach uses code within the activity's onCreate method, while the second leverages an XML attribute. Both methods achieve the same goal of preventing the soft keyboard from appearing when the user interacts with the specified NumberPicker.


MainActivity.kt

package com.cfsuman.kotlintutorials

import android.app.Activity
import android.os.Bundle
import android.widget.NumberPicker


class MainActivity : Activity() {
    private lateinit var numberPicker:NumberPicker
    private lateinit var numberPicker2:NumberPicker

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

        // get the widgets reference from XML layout
        numberPicker = findViewById(R.id.numberPicker)
        numberPicker2 = findViewById(R.id.numberPicker2)

        // set first number picker minimum and maximum value
        numberPicker.minValue = 0
        numberPicker.maxValue = 20


        // display string values to the number picker
        // at first, initialize a new array instance with string values
        val colors = arrayOf("Red", "Green", "Blue", "Yellow",
            "Magenta", "Black", "Pink")

        // set the number picker minimum and maximum values
        numberPicker2.minValue = 0
        numberPicker2.maxValue = colors.size - 1

        // set the valued to be displayed in number picker
        numberPicker2.displayedValues = colors

        // disable soft keyboard programmatically
        numberPicker2.descendantFocusability =
            NumberPicker.FOCUS_BLOCK_DESCENDANTS
    }
}
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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#DCDCDC"
    android:padding="32dp">

    <!--
        disable soft keyboard in xml
        android:descendantFocusability="blocksDescendants"
    -->
    <NumberPicker
        android:id="@+id/numberPicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        android:descendantFocusability="blocksDescendants"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <NumberPicker
        android:id="@+id/numberPicker2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="32dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/numberPicker" />

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