我正在尝试使用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中检索float / double值。
答案 0 :(得分:5)
我刚刚使用您的代码进行了测试。 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);
答案 1 :(得分:0)
在科特林(Kotlin)中,您可以使用此方便的NumberPicker
扩展名来显示对话框-在自动换行的情况下,它将您的Double
值缩放到合适的Int
范围并在调用任何回调之前将Int
的值转换回Double
。因此,它基本上掩盖了NumberPicker
仅支持Int
的事实。只是感觉NumberPicker
实际上会支持Double
,请尝试一下!
这是片段扩展名,您可以复制并粘贴:
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) }
)