[Android]NumberPicker selected item change color

后端 未结 4 592
星月不相逢
星月不相逢 2021-01-17 20:09

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 st

4条回答
  •  遥遥无期
    2021-01-17 20:19

    I 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){
                }
            }
        }
    }
    

提交回复
热议问题