Android NumberPicker 设置环绕项目的项目数

Android NumberPicker set number of items to wrap items around

我试图在 TimePicker 中设置小时和分钟,但我发现 NumberPicker 中似乎需要最少的项目数才能使值环绕。

如果我没有那么多值(只有 4 个:“00”、“15”、“30”和“45”),如何将项目数设置为小于默认值?

下图显示的小时是正确的,但分钟是错误的。我需要像小时一样环绕分钟(即“00”之前的“45”)。

这是我的代码:

@SuppressLint("NewApi")
private void setTimePickerInterval(TimePicker timePicker) {
    try {
        Class<?> classForid = Class.forName("com.android.internal.R$id");

        Field fieldHr = classForid.getField("hour");
        mHourPicker = (NumberPicker) timePicker.findViewById(fieldHr.getInt(null));

        //set hours from 9am to 7pm (opening hours)
        mHourPicker.setMinValue(0);
        mHourPicker.setMaxValue(10);
        mDisplayedValuesHr = new ArrayList<String>();

        for (int i = 9; i < 20; i++) {
            mDisplayedValuesHr.add(String.format("%02d", i));
        }

        mHourPicker.setDisplayedValues(mDisplayedValuesHr.toArray(new String[0]));

        Field fieldMin = classForid.getField("minute");
        mMinutePicker = (NumberPicker) timePicker.findViewById(fieldMin.getInt(null));

        //set minutes in 15 mins interval
        mMinutePicker.setMinValue(0);
        mMinutePicker.setMaxValue(3);
        mDisplayedValuesMin = new ArrayList<String>();

        for (int i = 0; i < 60; i += TIME_PICKER_INTERVAL) {
            mDisplayedValuesMin.add(String.format("%02d", i));
        }

        mMinutePicker.setDisplayedValues(mDisplayedValuesMin.toArray(new String[0]));

    } catch (Exception e) {
        e.printStackTrace();
    }
}

可以显式调用setWrapSelectorWheel (boolean)触发NumberPicker的私有方法updateWrapSelectorWheel:

@SuppressLint("NewApi")
private void setTimePickerInterval(TimePicker timePicker) {
    try {
        Class<?> classForid = Class.forName("com.android.internal.R$id");

        Field fieldHr = classForid.getField("hour");
        mHourPicker = (NumberPicker) timePicker.findViewById(fieldHr.getInt(null));

        //set hours from 9am to 7pm (opening hours)
        mHourPicker.setMinValue(0);
        mHourPicker.setMaxValue(10);
        mDisplayedValuesHr = new ArrayList<String>();

        for (int i = 9; i < 20; i++) {
            mDisplayedValuesHr.add(String.format("%02d", i));
        }

        mHourPicker.setDisplayedValues(mDisplayedValuesHr.toArray(new String[0]));

        Field fieldMin = classForid.getField("minute");
        mMinutePicker = (NumberPicker) timePicker.findViewById(fieldMin.getInt(null));

        //set minutes in 15 mins interval
        mMinutePicker.setMinValue(0);
        mMinutePicker.setMaxValue(3);
        mDisplayedValuesMin = new ArrayList<String>();

        for (int i = 0; i < 60; i += TIME_PICKER_INTERVAL) {
            mDisplayedValuesMin.add(String.format("%02d", i));
        }

        mMinutePicker.setDisplayedValues(mDisplayedValuesMin.toArray(new String[0]));
        mMinutePicker.setWrapSelectorWheel(true);

    } catch (Exception e) {
        e.printStackTrace();
    }
}