Number Picker in Android

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
    [java]
    Button b = (Button) findViewById(R.id.button1);
    final NumberPicker np = (NumberPicker) findViewById(R.id.numberPicker1);
    [/java]
  • 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.
    [java]
    np.setMinValue(1);
    np.setMaxValue(20);
    [/java]
  • 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

[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;
}
}
[/java]

Leave a Comment

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