如何在Android中启用的NumberPicker中更改所选数字的颜色

时间:2016-11-07 18:21:55

标签: android numberpicker

我想在MyNumberPicker上实现此效果

enter image description here

到目前为止,我实现了一个NumberPicker类并更改了几个属性,但有趣的部分是:

public class NumberPicker extends android.widget.NumberPicker{

    public NumberPicker(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void addView(View child) {
        super.addView(child);
        updateView(child);
    }

    @Override
    public void addView(View child, int index, android.view.ViewGroup.LayoutParams params) {
        super.addView(child, index, params);
        updateView(child);
    }

    @Override
    public void addView(View child, android.view.ViewGroup.LayoutParams params) {
        super.addView(child, params);
        updateView(child);
    }

    private void updateView(View view) {
        if(view instanceof EditText){
            ((EditText) view).setTextSize(getResources().getDimension(R.dimen.numberpicker_text_size));
           ((EditText) view).setTextColor(ContextCompat.getColor(getContext(), R.color.colorPrimaryDark));

        }
    }

但我得到的效果是:

enter image description here

我将所有文本显示为蓝色(已选中,未选中,有效,无效)如何仅在启用的NumberPicker和所选值上获得此蓝色?

感谢您的支持

1 个答案:

答案 0 :(得分:1)

使用您想要的属性创建ColorStateList。然后将其应用于EditText

final ColorStateList colors = new ColorStateList(
                new int[][]{
                        new int[]{android.R.attr.state_selected},
                        new int[]{-android.R.attr.state_selected}
                },
                new int[]{selectedColorCode, defaultColor}
        );

((EditText) view).setTextColor(colors);