Search code examples
androidratingbar

RatingBar android - custom draw runtime


I have ratingbar shown in a list.

As people rate the items from 1 to 4 stars - the ratingbar should change either color of the stars or the background or overlay or something to symbolize the change (customer requirement in an organisation that's used to use colors to identify state, e.g. green = good)

I was thinking that changing the color of the stars would saisfy this. However, most of the solutions to this revolve around changing the default graphic used in the raing bar, and not how to ownerdraw after a rating has been changed by the user.


Solution

  • I suppose you're looking for color tint:

    ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
        @Override
        public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
            final LayerDrawable layerDrawable = (LayerDrawable) ratingBar.getProgressDrawable();
            int color;
            switch ((int) rating) {
                case 1:
                    color = Color.RED;
                    break;
                case 2:
                case 3:
                    color = Color.YELLOW;
                    break;
                case 4:
                default:
                    color = Color.GREEN;
                    break;
            }
            DrawableCompat.setTint(DrawableCompat.wrap(layerDrawable.getDrawable(2)), color);
        }
    });
    

    It works not very smooth, but it should be a point to start.

    enter image description here

    Also, you can set the color tint in touch listener - that way will be better for you, I guess:

    ratingBar.setOnTouchListener(new View.OnTouchListener() {
        private int lastColoredProgress = 0;
    
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int progress = ratingBar.getProgress();
            if (progress != lastColoredProgress) {
                lastColoredProgress = progress;
                final LayerDrawable layerDrawable = (LayerDrawable) ratingBar.getProgressDrawable();
                int color;
                switch (lastColoredProgress) {
                    case 0:
                    case 1:
                        color = Color.RED;
                        break;
                    case 2:
                    case 3:
                        color = Color.YELLOW;
                        break;
                    case 4:
                    default:
                        color = Color.GREEN;
                        break;
                }
                DrawableCompat.setTint(DrawableCompat.wrap(layerDrawable.getDrawable(2)), color);
            }
            return false;
        }
    });
    

    enter image description here