Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[Android]NumberPicker selected item change color

Tags:

android

Is it possible to change color of the selected item in numberpicker so each time a new center child TextView appear change its color to whatever I like I did not find any style or API expose about this ?

like image 626
Dimitar Ivanov Avatar asked Dec 17 '15 13:12

Dimitar Ivanov


Video Answer


1 Answers

enter image description hereI tried to follow many answers and all of them were setting the whole number's color.

I figured out how to change color only for selected number. set OnTouchListener in your NumberPicker.

numberPicker.setOnTouchListener(new OnTouchListener() {
                    @Override
                    public boolean onTouch(final View v, MotionEvent event) {
                        currentTouchAction = event.getAction();
                        if (currentTouchAction == MotionEvent.ACTION_UP) {
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if (currentTouchAction == MotionEvent.ACTION_UP) {
                                        setSelectedTextColor((NumberPicker)v, selectedColorRes);
                                    }
                                }
                            }, 300);
                        }
                        return false;
                    }
                });

and below code is for changing the selected number color. You might have to use 'performClick()' to dynamically apply the color.

And if you do that, the picker would immediately stop. So that's why I put postDelayed(300) above. User might drag number picker several times to select the profit number. If you put above postDelay() and wait for several milliseconds, it can be scrolled smoothly.

public void setSelectedTextColor(NumberPicker np, int colorRes) {
    final int count = np.getChildCount();
    for(int i = 0; i < count; i++){
        View child = np.getChildAt(i);
        if(child instanceof EditText){
            try{
                Field selectorWheelPaintField = np.getClass().getDeclaredField("mSelectorWheelPaint");
                selectorWheelPaintField.setAccessible(true);
                ((EditText) child).setTextColor(mContext.getResources().getColor(colorRes));
                np.performClick();
            }
            catch(NoSuchFieldException e){
            }
            catch(IllegalArgumentException e){
            }
        }
    }
}
like image 184
youngwoon Avatar answered Oct 03 '22 19:10

youngwoon