androidonclicklistenernumberpicker

Adding a listener to a number picker widget


I am working on integrating a number picker to my application. The activity displays a list of items each with a number picker. The user can increase or decrease the quantity using the number picker. As they do this I would like to update a TextView showing the price.

I ran into difficulty when trying to achieve this. I made a simple project and attempted to try and display a toast message when the user clicked on the widget but to no avail.

My guess is that the number widget is not treated like a button therefor a click listener does not work? I would appreciate any advice in regards to adding a listener.

Below is my code:

NumberPicker np;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    np = (NumberPicker)findViewById(R.id.numberPicker1);
    np.setMaxValue(99);
    np.setMinValue(0);
    np.setValue(50);

    np.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Toast.makeText(v.getContext(), "Number selected", Toast.LENGTH_SHORT).show();
        }
    });
}

Solution

  • To set listener with Picker, your activity must implement the picker interface listener. (Actually, your activity is not mandatory to implement the interface, you can also use anonymous inner method. Whatever works.)

    So in your activity:

    public class MainActivity extends Activity implements NumberPicker.OnValueChangeListener {
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            NumberPicker np = (NumberPicker)findViewById(R.id.numberPicker1);
            np.setMaxValue(99);
            np.setMinValue(0);
            np.setValue(50);
            np.setOnValueChangedListener(this);
    
        }
    
        public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
            Toast.makeText(this, "change", Toast.LENGTH_SHORT).show();
        }
    }