数字选择器开始改变值几秒钟

时间:2017-01-20 16:05:11

标签: android android-widget

我想要一个数字选择器开始自动更改值几秒钟。

   private void changeValueByOne(final NumberPicker higherPicker, final boolean increment) {

    Method method;
    try {
        // refelction call for
        // higherPicker.changeValueByOne(true);
        method = higherPicker.getClass().getDeclaredMethod("changeValueByOne", boolean.class);
        method.setAccessible(true);
        method.invoke(higherPicker, increment);

    } catch (final NoSuchMethodException e) {
        e.printStackTrace();
    } catch (final IllegalArgumentException e) {
        e.printStackTrace();
    } catch (final IllegalAccessException e) {
        e.printStackTrace();
    } catch (final InvocationTargetException e) {
        e.printStackTrace();
    }
}

我实现了这个方法并尝试了

        Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    changeValueByOne(wp,true);
                }
            });
        }
    };
    thread.start();

但是不行。

我想作为老虎机有效。

1 个答案:

答案 0 :(得分:1)

为什么不能简单地将值设置为递增值?像这样:

private void changeValueByOne(final NumberPicker higherPicker) {
   int oldValue = higherPicker.getValue();
   higherPicker.setValue(oldValue++);
}

修改

以下是您反映的方法的来源:

private void changeValueByOne(boolean increment) {
    if (mHasSelectorWheel) {
        mInputText.setVisibility(View.INVISIBLE);
        if (!moveToFinalScrollerPosition(mFlingScroller)) {
            moveToFinalScrollerPosition(mAdjustScroller);
        }
        mPreviousScrollerY = 0;
        if (increment) {
            mFlingScroller.startScroll(0, 0, 0, -mSelectorElementHeight, SNAP_SCROLL_DURATION);
        } else {
            mFlingScroller.startScroll(0, 0, 0, mSelectorElementHeight, SNAP_SCROLL_DURATION);
        }
        invalidate();
    } else {
        if (increment) {
            setValueInternal(mValue + 1, true);
        } else {
            setValueInternal(mValue - 1, true);
        }
    }
}

您可以看到,如果mHasSelectorWheel = true,它会调用startScroll方法。换句话说,听起来您的NumberPicker有mHasSelectorWheel = false,在这种情况下,鉴于您当前的实施,您将失去运气。建议您查看自定义可滚动数字选择器小部件。