Getting Float/double From Numberpicker
I am trying the https://github.com/SimonVT/android-numberpicker library and the reference is https://developer.android.com/reference/android/widget/NumberPicker.html#getValue%28%29
Solution 1:
I just tested using your code. getValue() actually returns the index of the item selected (only when you set the displayed values). All you'll need to do is parse the string and you will have what you wanted.
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);
Solution 2:
In Kotlin, you can use this handy NumberPicker
extension which presents a dialog – under the wraps it scales your Double
values into a fitting Int
range and converts the Int
values back to Double
s before calling any of the callback. So it basicallly hides away the fact that NumberPicker
only supports Int
. It just feels like NumberPicker
would actually support Double
, try it out!
Here's the Fragment extension you can to copy & paste:
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()
}
Then you can use it like this:
showNumberPickerDialog(
title = "Your Weight",
value = 75.0, // in kilogramsrange = 10.0 .. 300.0,
formatToString = { "$it kg" },
valueChooseAction = { saveNewWeight(it) }
)
Post a Comment for "Getting Float/double From Numberpicker"