I was working on a new, yet to be released, Android app that necessitated the need for the new NumberPicker widget introduced in Android 3.0. Unfortunately, there are almost no examples of its use floating around and the documentation in the Android API is extremely lacking. Thus, I spent a few hours of trial and error figuring out how it worked.
My goal: Use a NumberPicker to allow a user to select a multiple of 5 in the range 0-100.
First up: The XML.
1
2
3
4
<NumberPicker android:id="@+id/np"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:width="100dip"/>
The XML for our NumberPicker looks very similar to any other Android widget. By default the NumberPicker is set up for displaying two digit numbers, but our last number in this case, 100, is three digits. Hence, the leading 1 in 100 will be cutoff and only 00 is displayed in the NumberPicker. To remedy this, the width is set to 100dip which is wide enough to allow for three digit numbers.
Because of the lack of XML properties for the NumberPicker, we must do all of the configuration for it in code. Speaking of which…