Tuesday, September 29, 2020

android kotlin - NumberPicker string values

MainActivity.kt

package com.example.jetpack

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)

        // 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: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" />

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