Jesús Ayala Jesús Ayala - 28 days ago 21
Android Question

How to change color for selected number in enabled NumberPicker in Android

I want to achieve this effect on MyNumberPicker

enter image description here

so far I implemented a NumberPicker class and changed several properties, but the interesting part is here:

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));

}
}


but the effect I get is this:

enter image description here

I get all text in blue (selected, no selected, active, inactive) how to get this blue only on enabled NumberPicker and selected value?

thanks for the support

Answer

Create a ColorStateList with your desired attributes. Then apply those to the 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);