在NumberPicker中设置不同的文本颜色到不同的选项(android)

时间:2015-06-08 13:09:11

标签: android numberpicker

我想为四套扑克牌(作为unicode)创建一个NumberPicker,其中两套西装用红色字体显示,另外两套用黑色字体显示。

关于NumberPicker和text-color的所有解决方案都会更改选择器的所有元素的颜色。

现在,我已经做到了,当价值变化时,颜色也会发生变化。这样可以使所选的套装颜色正确,但也会使相邻的套装变成错误的颜色。

有没有办法在NumberPicker

中有交替的颜色

提前致谢:)

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 个答案:

没有答案