I've created an application for Android, in which there is a NumberPicker. And I need to change the value of this NumberPicker but with a smooth animation like when you touch it and change its value.
For example, assume the current value is 1 and it's going to be 5, I want the NumberPicker to spin from 1 to 2 then to 3 and so on. But I want it to spin not just instantly change the values!
If I use the following code:
numberPicker.setValue(5);
its value will instantly change to 5, but I want it to roll up from 1 to 5 like when you manually touch it and make it spin.
I don't believe that this is natively supported. I thought of a 'messy' way of doing it manually:
You can use the NumberPicker's scrollBy(int x, int y) function called iteratively to make the effect of the animation.
Some things to take into account:
I haven't made animations myself in Android, but there is a very good API since Honeycomb which probably makes it easy to accomplish this.
I am sorry, but this is the easiest I could think of!
EDIT: To convert from 'dp' to pixels:
What you'll have to do is test calling scrollBy(0, pxFromDp(dp)) with different 'dp' values, until you get the exact one that moves the NumberPicker up one number. Once you get that value, you can create your animation method that when moving up X numbers will scroll X times this dp distance.
Please ask again if you don't understand it completely :)
I solved it via refelction
works perfect. I don't know why this method is private
There is private method inside NumberPicker, which is
You can make it public and use it. You can see this method in action when pressing UP or DOWN arrow of NumberPicker. Probably it's not what you are looking for since this method does not give much control of animation, but it's definitelly better than setValue. Without any animation setValue looks terrible to user.
Thank @passsy. Inspired his answer: This solution supports multiple increment/decrement steps. Also, can be executed with a start delay and for multiple numberPickers (without extra coding).
The usage: