It is so simple, and it is so hard at the same time.
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] values = {"d", "aa", "a", "b"};
NumberPicker numberPicker = findViewById(R.id.number_picker);
numberPicker.setDisplayedValues(values);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(3);
numberPicker.setValue(2); // Want to show "a" in number picker
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<NumberPicker
android:id="@+id/number_picker"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Result

Some more cases:
And when I click to anywhere inside the number picker, the "aa"'ish becomes "a" as expected. However, try putting numberPicker.performClick() after the setValue(2) method won't help.
This looks so simple but it is driving me nuts. Please help me.
tyr to create your own function to modify the data to be set on NumberPicker before set on NumberPicker.This function prevents any string to be substring of any string from the given array to be set on NumberPicker
modifyDataForNumberPicker(values);
numberPicker.setDisplayedValues(values);
private void modifyDataForNumberPicker(String[] dataList){
int i=0;
for(String data : dataList){
int pos = i++;
dataList[pos] = data+" ";
}
}
the get the value clicked in the NumberPicker
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
String selectedvalue = values[newVal]
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With