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();
        }
    });
}
有帮助吗?

解决方案

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();
    }
}

其他提示

For the newer Android developers (like me), the activity itself isn't required to implement the listener. It just needs to be passed into the setOnValueChangedListener().

This helps avoid too many implements and too many overlapping @Overrides.

Example:

// Number Picker
NumberPicker np = (NumberPicker) getView().findViewById(R.id.numberPicker1);
np.setMinValue(0);
np.setMaxValue(35);

np.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
    @Override
    public void onValueChange(NumberPicker numberPicker, int i, int i2) {

        Toast.makeText(this, "Value was: " + Integer.toString(i) + " is now: " + Integer.toString(i2), Toast.LENGTH_SHORT).show();

    }
});

you will need to set NumberPicker.setOnValueChangedListener to notified on change of the current value of NumberPicker

see this example how we set setOnValueChangedListener for NumberPicker

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top