Set different text colors to different options in NumberPicker (android)

753 views Asked by At

I would like to create a NumberPicker for the four suits of playing cards (as unicode) with 2 of the suits displaying with red font and the other 2 with black font.

All the solutions regarding NumberPicker and text-color change the color of all the elements of the picker.

Right now, I have made it so that when the value changes, the color also changes. This allows the suit selected to be in the correct color but will also change the adajacent suits to be the wrong color.

Is there any way to have alternating colors in NumberPicker?

Thanks in advance:)

String[] suits = {
  "\u2665", "\u2660", "\u2666", "\u2663"
};
suitPicker.setMaxValue(suits.length - 1);
suitPicker.setMinValue(0);
suitPicker.setDisplayedValues(suits);
suitPicker.setWrapSelectorWheel(true);

suitPicker.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
setNumberPickerTextColor(suitPicker, getResources().getColor(R.color.GreyDark));

suitPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {@
  Override
  public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
    if (newVal % 2 == 0) {
      setNumberPickerTextColor(suitPicker, getResources().getColor(R.color.Red));
    } else {
      setNumberPickerTextColor(suitPicker, getResources().getColor(R.color.GreyDark));
    }
  }
});

.....

public boolean setNumberPickerTextColor(NumberPicker numberPicker, int color) {
  int count = numberPicker.getChildCount();
  for (int i = 0; i < count; i++) {
    View child = numberPicker.getChildAt(i);
    if (child instanceof EditText) {
      try {
        Field selectorWheelPaintField = numberPicker.getClass()
          .getDeclaredField("mSelectorWheelPaint");
        selectorWheelPaintField.setAccessible(true);

        selectorWheelPaintField.setAccessible(true);
        ((Paint) selectorWheelPaintField.get(numberPicker)).setColor(color);
        ((EditText) child).setTextColor(color);
        numberPicker.invalidate();
        return true;
      } catch (NoSuchFieldException e) {
        Log.w("setNumberPickerTextColor", e);
      } catch (IllegalAccessException e) {
        Log.w("setNumberPickerTextColor", e);
      } catch (IllegalArgumentException e) {
        Log.w("setNumberPickerTextColor", e);
      }
    }
  }
  return false;
}
0

There are 0 answers