Implementing OnValueChange to a NumberPicker in Android

TheMcMurder picture TheMcMurder · Apr 13, 2013 · Viewed 13.2k times · Source

I"m trying to add the onValueChangeListener to my number picker (np1) in android 4.2.2.

Here's what I have so far

public class main extends Activity  {
ViewFlipper vf = null;
HttpClient client = null;
private ArrayList<String> captionList = new ArrayList<String>();
ListView lv = null;
private String custid = null;
ImageView iv = null;
private int vfloginview = 0;
private int vflistview = 0;
private boolean vfsentinal = false;
NumberPicker np1 = null;
TextView totalcost = null;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mystuffmobile);
    vf = (ViewFlipper) findViewById(R.id.vf);
    client = new DefaultHttpClient();
    lv = (ListView) findViewById(R.id.lv);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    np1 = (NumberPicker) findViewById(R.id.np1);
    np1.setMinValue(1);
    np1.setMaxValue(400);
    //np1.setOnValueChangedListener;    
    //np1.setOnValueChangedListener(onValueChange);

}

to try to test it's functionality I've been using this

public void onValueChange (NumberPicker np1, int oldVal, int newVal) {
    Log.v("NumberPicker", np1.getValue() +"");
}

Does anyone know an easy way to implement this listener without having my main activity implement NumberPicker.OnValueChangeListener?

Note: the only reason I'm opposed to having my main activity implement NumberPicker.OnValueChangeListener is because then I have to set main to abstract and my application won't run.

Answer

Bill Mote picture Bill Mote · Apr 13, 2013

You're going to do this just like a click listener on a button.

np1.setOnValueChangedListener(new OnValueChangeListener() {
    @Override
    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
        // do something here
    }
});

A fully working example can be found here: http://samplecodez.com/android/numberpicker.php

Some stylistic points ...

  • Main should be capitalized and it's a good practice to make it more descriptive like MainActivity.
  • Use fields only when necessary. I'm guessing you're not using most of those variables outside of onCreate() so make them local variables instead.
  • TextView totalCost is your best named variable of the lot :) Consider using verbose names. You'll thank yourself 6 months down the road when you look back at this code for the first time in a long time.
  • No magic values (or Strings)! Create a constant for your min and max values and those should be private static final int with the your fields.
  • In Eclipse setup the java save actions in preferences to auto format all lines of code when you save.

Of course none of those things will make your code run any better, but it sure will be easier to read.