Friday, September 25, 2020

android kotlin - Disable soft keyboard on NumberPicker

MainActivity.kt

package com.example.jetpack

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)

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

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