Chinmay Sarupria Chinmay Sarupria - 1 year ago 141
Android Question

How to call Number Picker onvaluechange method from button onclick?

NumberPicker in xml:

android:layout_weight="1" />

And here is button:

android:text="Any text!"
android:background="@drawable/round_button" />

OnValueChangedListener on numberpicker:

//Set a value change listener for NumberPicker
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
public void onValueChange(NumberPicker picker, int oldVal, int newVal){

//Statement goes here...


Whenever user changes the value, the statements in onvaluechange execute like they should. But I want to update the value of number picker using a button.

Now, I have set a onclicklistener to button:

b1 = (Button) rootView.findViewById(;
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//Increment NumberPicker value by 1
numberPicker.setValue(numberPicker.getValue() + 1);

This works, it increments the value of number picker by 1 but it doesn't notify the numberpicker that the value has changed so as a result, the code inside
doesn't get executed. Only when the user manually scrolls the number picker does the statements execute. I want the same to happen when button is clicked.

Answer Source

This is actually a correct behavior of NumberPicker widget. If you look inside its source code, you will see this:

public void setValue(int value) {
    setValueInternal(value, false);

and here is setValueInternal method:

private void setValueInternal(int current, boolean notifyChange) {
    if (mValue == current) {
    // Wrap around the values if we go past the start or end
    if (mWrapSelectorWheel) {
        current = getWrappedSelectorIndex(current);
    } else {
        current = Math.max(current, mMinValue);
        current = Math.min(current, mMaxValue);
    int previous = mValue;
    mValue = current;
    if (notifyChange) {
        notifyChange(previous, current);

as you can see setValueInternal is called by setValue method with notifyChange = false and this is why your listener doesn't get notified. setValueInternal is declared as private so you can't call it from your code without using reflection.

My suggestion is to do something like this:

private class NumberPickerListener implements NumberPicker.OnValueChangeListener {

    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
      //your code

then just declare a NumberPickerListener variable and use it inside your click listener:

final NumberPickerListener numberListener = new NumberPickerListener();

b1.setOnClickListener(new View.OnClickListener() {
    public void onClick(View view) {
        int oldValue = numberPicker.getValue();
        numberPicker.setValue(oldValue + 1);
        numberListener.onValueChange(numberPicker, oldValue, oldValue+1);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download