Android NumberPicker Using Kotlin With Example

In this article, we will learn about android NumberPicker using Kotlin. We will go through various example that demonstrates how to use different attributes of NumberPicker. For example,

In this article, we will get answer to questions like –

  • What is NumberPicker?
  • Why should we consider NumberPicker while designing ui for any app?
  • What are possibilities using NumberPicker while designing ui? etc.

Let’s have a quick demo of things we want to cover in this tutorial –

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

We can define android NumberPicker widget as below –

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

Now, how do we use NumberPicker in android application ?

Creating New Project

At first, we will create an application.
So, follow steps below to create any android project in Kotlin –

Step Description
1. Open Android Studio (Ignore if already done).
2. Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next.
3. In next screen, select project name as NumberPicker. Then, fill other required details.
4. Then, clicking on Finish button creates new project.

Newbie in Android ?

Some very important concepts (Recommended to learn before you move ahead)

Before we move ahead, we need to setup for viewBinding to access Android NumberPicker Using Kotlin file without using findViewById() method.

Setup ViewBinding

Add viewBinding true in app/build.gradle file.

 
 android { 
 	// OTHER CODE... 
 	buildFeatures { 
 		viewBinding true 
 	} 
 } 
 

Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.

 
 class MainActivity : AppCompatActivity() { 
 	
 	private lateinit var binding: ActivityMainBinding 
 	
 	override fun onCreate(savedInstanceState: Bundle?) { 
 		super.onCreate(savedInstanceState) 
 		binding = ActivityMainBinding.inflate(layoutInflater) 
 		val view = binding.root 
 		setContentView(view) 
 	} 
 } 
 

Now, we can access view in Kotlin file without using findViewById() method.

Using NumberPicker in Kotlin

Follow steps below to use NumberPicker in newly created project –

  • Open res/values/strings.xml file. Then, add below code into it.
    <resources>
        <string name="app_name">NumberPicker</string>
    </resources>
    
  • Open res/layout/activity_main.xml file. Then, add below code in it –
    <?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"
        tools:context=".MainActivity">
    
        <NumberPicker
            android:id="@+id/numberPicker"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
  • We can provide two types of data in NumberPicker. They are –

    • a. Only Integer Values
    • b. Array of String values

    We will see each type one by one.

  • Show Only Integer Values in NumberPicker

    Open MainActivity.kt. Then, write below code in it –

    package com.tutorialwing.numberpicker
    
    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import android.widget.Toast
    import com.tutorialwing.numberpicker.databinding.ActivityMainBinding
    
    class MainActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityMainBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		val view = binding.root
    		setContentView(view)
    
    		setupNumberPicker()
    	}
    
    	private fun setupNumberPicker() {
    		val numberPicker = binding.numberPicker
    		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.

    Now, run the application. We will get output as below –

    Tutorialwing Kotlin NumberPicker Integer Output Android NumberPicker Using Kotlin With Example

    Tutorialwing Kotlin NumberPicker Integer Output

  • Show 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 androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import android.widget.Toast
    import com.tutorialwing.numberpicker.databinding.ActivityMainBinding
    
    class MainActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityMainBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		val view = binding.root
    		setContentView(view)
    
    		setupNumberPickerForStringValues()
    	}
    
    	private fun setupNumberPickerForStringValues() {
    		val numberPicker = binding.numberPicker
    		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.

    Now, run application. We will get below output –

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

    Tutorialwing Kotlin NumberPicker String Output

Different Attributes of NumberPicker in XML

Now, we will see how to use different attributes of Android NumberPicker using Kotlin to customise it –

Set Id of NumberPicker

Many a time, we need id of View to access it in kotlin file or create ui relative to that view in xml file. So, we can set id of NumberPicker using android:id attribute like below –

    <NumberPicker
        android:id="@+id/numberPicker_ID"
        />

Here, we have set id of NumberPicker as numberPicker_ID using android:id=”” attribute. So, if we need to reference this NumberPicker, we need to use this id – numberPicker_ID.
Learn to Set ID of NumberPicker Dynamically

Set Width of NumberPicker

We use android:layout_width=”” attribute to set width of NumberPicker.
We can do it as below –

    <NumberPicker
        android:id="@+id/numberPicker_ID"
        android:layout_width="wrap_content"
        />

Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).
Learn to Set Width of NumberPicker Dynamically

Set Height of NumberPicker

We use android:layout_height=”” attribute to set height of NumberPicker.
We can do it as below –

    <NumberPicker
        android:id="@+id/numberPicker_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.
Learn to Set Height of NumberPicker Dynamically

Set Padding of NumberPicker

We use android:padding=”” attribute to set padding of NumberPicker.
We can do it as below –

    <NumberPicker
        android:id="@+id/numberPicker_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        />

Here, we have set padding of 10dp in NumberPicker using android:padding=”” attribute.
Learn to Set Padding of NumberPicker Dynamically

Set Margin of NumberPicker

We use android:layout_margin=”” attribute to set margin of NumberPicker.
We can do it as below –

    <NumberPicker
        android:id="@+id/numberPicker_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        />

Here, we have set margin of 10dp in NumberPicker using android:layout_margin=”” attribute.
Learn to Set Margin of NumberPicker Dynamically

Set Background of NumberPicker

We use android:background=”” attribute to set background of NumberPicker.
We can do it as below –

    <NumberPicker
        android:id="@+id/numberPicker_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff0000"
        />

Here, we have set background of color #ff0000 in NumberPicker using android:background=”” attribute.
Learn to Set Background of NumberPicker Dynamically

Set Visibility of NumberPicker

We use android:visibility=”” attribute to set visibility of NumberPicker.
We can do it as below –

    <NumberPicker
        android:id="@+id/numberPicker_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        />

Here, we have set visibility of NumberPicker using android:visiblity=”” attribute. Visibility can be of three types – gone, visible and invisible
Learn to Set Visibility of NumberPicker Dynamically

Till now, we have see how to use android NumberPicker using Kotlin. We have also gone through different attributes of NumberPicker to perform certain task. Let’s have a look at list of such attributes and it’s related task.

Different Attributes of Android NumberPicker Widget

Below are the various attributes that are used to customise android NumberPicker Widget. However, you can check the complete list of attributes of NumberPicker in it’s official documentation site. Here, we are going to list some of the important attributes of this 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

We have seen different attributes of NumberPicker and how to use it. If you wish to visit post to learn more about it

Thus, we have seen what is NumberPicker, how can we use android NumberPicker using Kotlin ? etc. We also went through different attributes of android NumberPicker.

Leave a Reply