NumberPicker Widget for Android
UPDATE: A new post has been added that improves the code used for the NumberPicker, you’ll find the update here: http://www.quietlycoding.com/?p=32
All source code used in this tutorial is licensed under Apache 2.0 License
I have seen quite a few Android developers looking to use a number picker widget in their applications. Google has an internal widget not available through the public api that fits the user interface of the system. This tutorial will provide developers with an easy solution to their number picking needs.
To get started download the NumberPicker files here: numpicker.zip
First thing to do is make sure you copy over the resources into your project. You’ll need both the xml and drawable files. You do not need to include the picker_pref.xml file if you do not plan on using the picker in a preference.
Next you’ll need to add the two .java files into your project. Make sure you change the package name and the import of the R class to match your project. One thing to note is the xml files reference the .java classes so you’ll have to update the package names there as well so the compile process can find everything.
Once you have all the namespace issues resolved you can then add this widget into your UI as you would any other Android widget.
I modified the widget slightly by adding a min and a max value to the widget. This can be adjusted and the code I added is below for reference:
In the constructor of NumberPicker at the end you’ll see these two lines:
mStart = DEFAULT_MIN;
mEnd = DEFAULT_MAX;
At the top of the java file I have declared the DEFAULT_MAX and DEFAULT_MIN as such:
private static final int DEFAULT_MAX = 200;
private static final int DEFAULT_MIN = 0;
As you can see its relatively simple to get started using the NumberPicker to enhance your UI. If you have any questions about the implementation feel free to comment. I’ve also created a very simple demo application that uses the files from this tutorial. You can grab the source code for the demo from My Github or as a zip file here.
Here is a screenshot of what the NumberPicker looks like, this was included as part of an app’s preferences: