问题
When the numberpicker is loaded, the default value is not appearing on the screen until touched.
Once touched, everything works fine.Any help appreciated.
Also if the formatter is removed, it works fine.
dialog.xml
<NumberPicker
android:id="@+id/number_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/apply_button"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/number_picker"
android:text="@string/ok_string" />
Here is the activity code:
final NumberPicker np = (NumberPicker) d.findViewById(R.id.number_picker);
np.setMaxValue(50);
np.setMinValue(0);
np.setWrapSelectorWheel(true);
np.setOnValueChangedListener(this);
np.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
np.setFormatter(new NumberPicker.Formatter() {
@Override
public String format(int i) {
if (i == 25)
return "0";
else
return String.valueOf(i - 25);
}
});
np.setValue(25);
Thanks in advance
回答1:
@Renjith
Thank for the link, but I think you should link the code or even paste it here. https://code.google.com/p/android/issues/detail?id=35482#c9
Field f = NumberPicker.class.getDeclaredField("mInputText");
f.setAccessible(true);
EditText inputText = f.get(mPicker);
inputText.setFilters(new InputFilter[0]);
回答2:
The issue seems to a bug in NumberPicker widget.
And I have solved it using method 2 described here.
回答3:
I found a solution for this bug in NumberPicker that works in APIs 18-26 without using reflection and without using setDisplayedValues()
here.
回答4:
I had the same problem and I was using NumberPicker
with Strings.
My problem was that after the activity was opened with a transition the the default value in the number picker was invisible, even though i was setting the picker values with picker.setDisplayedValues(list.toStringsArray())
So for me the solution was the following:
private void populatePicker(NumberPicker picker, String[] strings, int index) {
picker.setDisplayedValues(null);
picker.setMinValue(0);
picker.setMaxValue(strings.length - 1);
picker.setDisplayedValues(strings);
picker.setValue(index);
try {
Field field = NumberPicker.class.getDeclaredField("mInputText");
field.setAccessible(true);
EditText inputText = (EditText) field.get(picker);
inputText.setVisibility(View.INVISIBLE);
} catch (Exception e) {
e.printStackTrace();
}
}
回答5:
Here's the accepted answer written in Kotlin in a single line:
// 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()
Note that I recommend to keep the comment line to document why this code is needed.
来源:https://stackoverflow.com/questions/27343772/android-numberpicker-default-value-not-coming