謝謝@passsy。啓發他的回答:該解決方案支持多個遞增/遞減步驟。此外,可以用啓動延遲和執行多個編號(無需額外編碼)。
class IncreaseValue {
private int counter = 0;
private final NumberPicker picker;
private final int incrementValue;
private final boolean increment;
private final Handler handler = new Handler();
private final Runnable fire = new Runnable() { @Override public void run() { fire(); } };
/*public*/ IncreaseValue(final NumberPicker picker, final int incrementValue) {
this.picker = picker;
if (incrementValue > 0) {
increment = true;
this.incrementValue = incrementValue;
} else {
increment = false;
this.incrementValue = -incrementValue;
}
}
/*public*/ void run(final int startDelay) {
handler.postDelayed(fire, startDelay); // This will execute the runnable passed to it (fire)
// after [startDelay in milliseconds], ASYNCHRONOUSLY.
}
private void fire() {
++counter;
if (counter > incrementValue) return;
try {
// refelction call for
// picker.changeValueByOne(true);
final Method method = picker.getClass().getDeclaredMethod("changeValueByOne", boolean.class);
method.setAccessible(true);
method.invoke(picker, increment);
} catch (final NoSuchMethodException | InvocationTargetException |
IllegalAccessException | IllegalArgumentException e) {
Log.d(TAG, "...", e);
}
handler.postDelayed(fire, 120); // This will execute the runnable passed to it (fire)
// after 120 milliseconds, ASYNCHRONOUSLY. Customize this value if necessary.
}
}
用法:
// Suppose picker1 as a NumberPicker
IncreaseValue increasePicker1 = new IncreaseValue(picker1, 10); // So picker1 will be increased 10 steps.
increasePicker1.run(0); // Increase immediately. If you want to run it from onCreate(), onStart() or ... of your activity, you will probably need to pass a positive value to it (e.g. 100 milliseconds).
用你的技術來解決[這個問題](http://stackoverflow.com/q/17708325/473232)。謝謝。 – dgel
對不起,以恢復舊的線程,但會有一個簡單的方法來獲得這個增加NumberPicker遞減,而不是越來越多? 編輯:明白!只需要將參數改爲false而不是true。 – intA
我很自豪能夠復活這個舊線程。兩年後,這對我有用!我開始想知道爲什麼幾個組件中的很多功能都是私有的。這幾乎令人沮喪。 –