Tuesday, September 29, 2020

android kotlin - NumberPicker divider height

MainActivity.kt

package com.example.jetpack

import android.content.res.Resources
import android.os.Bundle
import android.widget.NumberPicker
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)

        // 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:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FEFEFA"
    tools:context=".MainActivity">

    <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>