android – SCROLL_ STATE_ Numberpicker. Getvalue() on idle may not be the last updated value
When the user completes the scrolling selection on numberpicker, I am using the following function to detect the last final value. Then getvalue() will update the latest value
numberPicker.setOnScrollListener(new NumberPicker.OnScrollListener() {
@Override
public void onScrollStateChange(NumberPicker numberPicker, int scrollState) {
if (scrollState == NumberPicker.OnScrollListener.SCROLL_STATE_IDLE) {
int value = numberPicker.getValue();
}
}
});
However, then I found that if the end of the scrolling touch is not at the determined position of a value, but between two values (for example, between 1 and 2, but slightly close to 2), after abandoning the scrolling, the function trigger captures getValue as 1, but the scrolling will automatically complete its scrolling to focus on 2. Therefore, the last updated value of numberpicker is then set to 2 (not 1, i.e. captured in the above function)
How can I get the latest updated value of numberpicker? Or maybe it's a way to detect the final automatic scrolling of numberpicker (when it focuses on a specific value)?
For reference only. One option is to use setonvaluechangedlistener. However, this is not ideal for my situation, because it will capture each value change even if numberpicker scrolling is in progress
thank you!
resolvent:
To solve this problem, I added onvaluechange and onscrolllistener to numberpicker. I created private fields to maintain the current scrolling state. Both listener interfaces are implemented by the same class. Onvaluechangelistener method checks the scrolling state. If it is idle - execute some code. This suits me. It looks like this:
public class MainActivity extends AppCompatActivity {
private NumberPicker np;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
np = (NumberPicker) findViewById(R.id.picker);
PickerListener listener = new PickerListener();
np.setOnScrollListener(listener);
np.setOnValueChangedListener(listener);
}
private void update(){
//your code here
}
private class PickerListener implements NumberPicker.OnScrollListener, NumberPicker.OnValuechangelistener {
private int scrollState=0;
@Override
public void onScrollStateChange(NumberPicker view, int scrollState) {
this.scrollState=scrollState;
if (scrollState==SCROLL_STATE_IDLE){
update();
}
}
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
if (scrollState==0){
update();
}
}
}