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();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With