Android NumberPicker Using Kotlin With Example

Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners. Also, if you are interested in content writing, you can mail us at tutorialwing@gmail.com.

Hello Readers! In this post, we are going to learn about android numberPicker using kotlin in any android application. We will also learn about different attributes of android numberPicker that can be used to customise this widget.

Output

Tutorialwing Kotlin NumberPicker Integer Output Android NumberPicker Using Kotlin With Example

Tutorialwing Kotlin NumberPicker Integer Output

Tutorialwing Kotlin NumberPicker String Output Android NumberPicker Using Kotlin Showing Array Of String values

Tutorialwing Kotlin NumberPicker String Output

Getting Started

Android NumberPicker can be defined as below –

NumberPicker is a widge that allows us to select a number from predefined range.

Different Attributes of Android NumberPicker Widget

Some of the popular attributes of android numberPicker inherited from linearLayout are –

Sr. XML Attributes Description
1 android:divider Drawable to use as a vertical divider between buttons
2 android:gravity Defines how an object should be placed inside LinearLayout i.e. specifies position, CENTER, VERTICAL_CENTER, HORIZONTAL_CENTER etc. relative to the boundaries of the linearLayout
3 android:orientation Defines whether linearLayout should be column or row. i.e. views inside linearLayout will be aligned as horizontally or vertically.
4 android:weightSum Defines maximum weight sum

Some of the popular attribute of android numberPicker inherited from viewGroup are –

Sr. XML Attributes Description
1 android:animationCache Specifies whether layout animation should create a drawing cache for their children
2 android:clipChildren Specifies whether a child is limited to draw inside of its bounds or not
3 android:clipToPadding Specifies whether the ViewGroup will clip its children and resize (but not clip) any EdgeEffect to its padding, if padding is not zero
4 android:layoutMode Specifies layout mode of this viewGroup

Some of the popular attribute of android numberPicker inherited from View are –

Sr. XML Attributes Description
1 android:alpha Specifies alpha of the view
2 android:background Specifies background of the view
3 android:focusable Specifies whether view can take focus or not
4 android:id Specifies unique identifier of the view
5 android:padding Specifies padding of view
6 android:visibility Specifies whether this view is visible or not



Example of Android NumberPicker Using Kotlin

At first, we will create android application. Then, we will use numberPicker using kotlin in the application.

1. Creating New Project in Kotlin

Follow steps below to create new project. Please ignore the steps if you have already created the project.

Step Description
1. Open Android Studio.
2. Go to File => New => New Project. Write application name as NumberPicker. Then, check Include Kotlin Support and click next button.
3. Select minimum SDK you need. However, we have selected 17 as minimum SDK. Then, click next button
4. Then, select Empty Activity => click next => click finish.
5. You will get a newly created project successfully if you have followed steps properly.

Since we have a project now, we will modify xml and other files to use NumberPicker using kotlin in the application.

2. Modify values folder

Open res/values/strings.xml file. Then, add below code into it.

<resources>
	<string name="app_name">NumberPicker</string>
</resources>

3. Use NumberPicker Widget in xml file

Open src/main/res/layout/activity_main.xml file and add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="wrap_content"
	android:layout_marginTop="20dp"
	android:orientation="horizontal">

	<NumberPicker
		android:id="@+id/numberPicker"
		android:layout_width="0dp"
		android:layout_height="wrap_content"
		android:layout_weight="1"/>
</LinearLayout>

In activity_main.xml file, we have defined numberPicker widget. Now, we will access this widget in kotlin file and perform some operations in it.

We can provide two types of data in numberPicker. They are –
a. Only Integer Values
b. Array of String values

Now, we will see how we can provide each types of data in numberPicker.

4. Show Only Integer Values in NumberPicker

Open src/main/java/com.tutorialwing.numberpicker/MainActivity.kt file and add below code into it.

package com.tutorialwing.numberpicker

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.NumberPicker
import android.widget.Toast

class MainActivity : AppCompatActivity() {

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

        val numberPicker = findViewById<NumberPicker>(R.id.numberPicker)
        if (numberPicker != null) {
            numberPicker.minValue = 0
            numberPicker.maxValue = 10
            numberPicker.wrapSelectorWheel = true
            numberPicker.setOnValueChangedListener { picker, oldVal, newVal ->
                val text = "Changed from $oldVal to $newVal"
                Toast.makeText(this@MainActivity, text, Toast.LENGTH_SHORT).show()
            }
        }
    }
}

We have accessed numberPicker using kotlin file (i.e. MainActivity.kt file) widget. Then, we have set minValue, maxValue etc. in it. Note that we have set range of values using minValue and maxValue attributes. minValue is responsible to set minimum value and maxValue is responsible to set maximum value. We have also set a listener that displays toast message whenever there is change in value selection in numberPicker.

5. Show Array Of String Values in NumberPicker

Open src/main/java/com.tutorialwing.numberpicker/MainActivity.kt file and add below code into it.

package com.tutorialwing.numberpicker

import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.NumberPicker

class MainActivity : AppCompatActivity() {

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

        val numberPicker = findViewById<NumberPicker>(R.id.numberPicker)
        if (numberPicker != null) {
            val values = arrayOf("Blue", "Magenta", "Yellow", "Red", "Pink", "White", "Green", "Violet")
            numberPicker.minValue = 0
            numberPicker.maxValue = values.size - 1
            numberPicker.displayedValues = values
            numberPicker.wrapSelectorWheel = true
            numberPicker.setOnValueChangedListener { picker, oldVal, newVal ->
                val text = "Changed from " + values[oldVal] + " to " + values[newVal]
                Toast.makeText(this@MainActivity, text, Toast.LENGTH_SHORT).show()
            }
        }
    }
}

Here, we have provided an array of string values as a data in numberPicker. Attribute displayedValues is responsible to set data in the numberPicker.

Since AndroidManifest.xml file is very important in any android application, we are also going to see the content inside this file.

AndroidManifest.xml file

Code inside main/AndroidManifest.xml file is as below.

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.tutorialwing.numberpicker"
		  xmlns:android="http://schemas.android.com/apk/res/android">

	<application
		android:allowBackup="true"
		android:icon="@mipmap/ic_launcher"
		android:label="@string/app_name"
		android:roundIcon="@mipmap/ic_launcher_round"
		android:supportsRtl="true"
		android:theme="@style/AppTheme">
		<activity android:name=".MainActivity">
			<intent-filter>
				<action android:name="android.intent.action.MAIN"/>

				<category android:name="android.intent.category.LAUNCHER"/>
			</intent-filter>
		</activity>
	</application>

</manifest>

When we run the program, we will get output as shown above.

That’s end of our tutorial on Android NumberPicker using Kotlin.

Support Us

If you like Tutorialwing and would like to contribute, you can email an article on any educational topic at tutorialwing@gmail.com. We would love to publish your article. See your article on Tutorialwing and help others with your knowledge. Follow Facebook, LinkedIn, Google+, Twitter, Youtube for latest updates.
Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners