Number Picker in Android

This entry is part 43 of 50 in the series Android Development Primer

Often times in our applications ,we are going to need to let the user choose numeric values. Of course we can design a custom Dialog box with an Edit Text and let the user type in the values. However, Android provides a very neat tool to do this with style and ease, theĀ NumberPickerĀ tool.

Complete Source Code is at the bottom.

  • Create a new Project and remember to set the minimum API version to at least 11 i.e. Honeycomb. This is because the support for the Number Picker has been introduces since API 11.
  • Create a layout for an activity. Drag and drop a Number Picker and a button from the palette on the left.
  • Switch over to the Java file and define the button and the Number Picker
    Button b = (Button) findViewById(R.id.button1);
    final NumberPicker np = (NumberPicker) findViewById(R.id.numberPicker1);
    
  • Remember to make the Number Picker final.
  • Set the minimum and maximum values. This defines the range in which the user is supposed to enter the values.
    np.setMinValue(1);
    np.setMaxValue(20);
    
  • Set the onClickListener() attribute for the button to display the value currently selected. We use the getValue() method for retrieving the current value.
  • Save it and execute in a device or an emulator that is running Android Honeycomb or higher.

NPick

COMPLETE SOURCE CODE

MainActivity.java

package com.nero.mysecondapp;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.Toast;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Button b = (Button) findViewById(R.id.button1);
		final NumberPicker np = (NumberPicker) findViewById(R.id.numberPicker1);
	    np.setMinValue(1);
	    np.setMaxValue(20);
	    b.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Toast.makeText(getApplicationContext(), np.getValue()+"", Toast.LENGTH_SHORT).show();
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
}
Series Navigation<< Alarm Manager in AndroidTime Picker in Android >>

Leave a Reply

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

*

* Copy This Password *

* Type Or Paste Password Here *

44,549 Spam Comments Blocked so far by Spam Free Wordpress

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>