4

我正在尝试https://github.com/SimonVT/android-numberpicker库,参考是https://developer.android.com/reference/android/widget/NumberPicker.html#getValue%28%29 现在两个, API 级别 11 NumberPicker 在 getValue 方法中返回 int 值,SimonVT numberpicker 返回 int 值。

但是我使用以下代码在数字选择器中设置了双值:

String[] nums = {"1","1.5","2","2.5","3","3.5","4","4.5","5","5.5","6","6.5","7","7.5","8","8.5","9"};

final NumberPicker listeningScorenp = (NumberPicker) findViewById(R.id.listeningScore);
listeningScorenp.setMaxValue(nums.length-1);
listeningScorenp.setMinValue(0);
listeningScorenp.setWrapSelectorWheel(false);
listeningScorenp.setDisplayedValues(nums);

现在我被困在如何从 NUMberPicker 中检索浮点/双精度值。

4

2 回答 2

8

我刚刚使用您的代码进行了测试。getValue() 实际上返回所选项目的索引(仅当您设置显示值时)。你需要做的就是解析字符串,你就会得到你想要的。

String[] nums = {"1","1.5","2","2.5","3","3.5","4","4.5","5","5.5","6","6.5","7","7.5","8","8.5","9"};
int index = listeningScorenp.getValue();
String val = nums[index];
float selectedFloat = Float.parseFloat(val);
于 2013-08-29T03:17:36.420 回答
1

Kotlin中,您可以使用这个方便NumberPicker的扩展,它显示一个对话框 - 在包装下,它会将您的Double值缩放到合适的Int范围,并在调用任何回调之前将Int值转换回s。所以它基本上隐藏了只支持Double的事实。感觉真的会支持,试试看!NumberPickerIntNumberPickerDouble

这是您可以复制和粘贴的片段扩展

fun Fragment.showNumberPickerDialog(
    title: String,
    value: Double,
    range: ClosedRange<Double>,
    stepSize: Double,
    formatToString: (Double) -> String,
    valueChooseAction: (Double) -> Unit
) {
    val numberPicker = NumberPicker(context).apply {
        setFormatter { formatToString(it.toDouble() * stepSize) }
        wrapSelectorWheel = false

        minValue = (range.start / stepSize).toInt()
        maxValue = (range.endInclusive / stepSize).toInt()
        this.value = (value.toDouble() / stepSize).toInt()

        // NOTE: workaround for a bug that rendered the selected value wrong until user scrolled, see also: https://stackoverflow.com/q/27343772/3451975
        (NumberPicker::class.java.getDeclaredField("mInputText").apply { isAccessible = true }.get(this) as EditText).filters = emptyArray()
    }

    MaterialAlertDialogBuilder(context)
        .setTitle(title)
        .setView(numberPicker)
        .setPositiveButton("OK") { _, _ -> valueChooseAction(numberPicker.value.toDouble() * stepSize) }
        .setNeutralButton("Cancel") { _, _ -> /* do nothing, closes dialog automatically */ }
        .show()
}

然后你可以像这样使用它

showNumberPickerDialog(
    title = "Your Weight",
    value = 75.0, // in kilograms
    range = 10.0 .. 300.0,
    formatToString = { "$it kg" },
    valueChooseAction = { saveNewWeight(it) }
)
于 2020-01-12T12:39:55.227 回答