Get selected value from NumberPicker in android

How to get numberpicker widget user selected numeric digit and show using textview on screen.

In this tutorial we are creating NumberPicker widget and setting up that selected value into TextView dynamically. So when user scroll down or scroll up the NumberPicker it will set the value of NumberPicker into TextView at application run time. So here is the complete step by step tutorial for Get selected value from NumberPicker in android.

android-project-download-code-button

How to Get selected value from NumberPicker in android.

Code for MainActivity.java file.

 package com.numberpicker_android_examples.com;

import android.app.Activity;
import android.os.Bundle;
import android.widget.NumberPicker;
import android.widget.TextView;


public class MainActivity extends Activity {

 NumberPicker numberpicker;
 TextView textview;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 numberpicker = (NumberPicker)findViewById(R.id.numberPicker1);

 textview = (TextView)findViewById(R.id.textView1);
 
 numberpicker.setMinValue(0);
 
 numberpicker.setMaxValue(100);
 
 numberpicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
 @Override
 public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
 
 
 textview.setText("Selected Value is : " + newVal);
 }
 });
 
 }
}

Code for activity_main.xml layout file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.numberpicker_android_examples.com.MainActivity" >

 <NumberPicker
 android:id="@+id/numberPicker1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentTop="true"
 android:layout_centerHorizontal="true"
 />

 <TextView
 android:id="@+id/textView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_below="@+id/numberPicker1"
 android:layout_centerHorizontal="true"
 android:text="Selected Number Display here"
 android:textAppearance="?android:attr/textAppearanceLarge" 
 android:gravity="center"/>
 
</RelativeLayout>

Screenshot:

Get selected value from NumberPicker in android

Click here to download Get selected value from NumberPicker in android project with source code.

Leave a Reply

Your email address will not be published. Required fields are marked *