1

I'm trying to change RatingBar stars color but after migrating to Android API 23 my following codes don't work and give me an exception.

LayerDrawable ratingBarStars = (LayerDrawable) holder.ratingBar.getProgressDrawable();
        ratingBarStars.getDrawable(0).setColorFilter(mContext.getResources()
                                                             .getColor(R.color.accent), PorterDuff.Mode.SRC_ATOP);
        ratingBarStars.getDrawable(1).setColorFilter(mContext.getResources()
                                                             .getColor(R.color.accent), PorterDuff.Mode.SRC_ATOP);
        ratingBarStars.getDrawable(2).setColorFilter(mContext.getResources()
                                                             .getColor(R.color.accent), PorterDuff.Mode.SRC_ATOP);

And the Error is:

java.lang.ClassCastException: android.support.v4.graphics.drawable.DrawableWrapperHoneycomb cannot be cast to android.graphics.drawable.LayerDrawable
Alex
  • 1,623
  • 1
  • 24
  • 48
  • obviously you cannot cast .... you should check if `getProgressDrawable()` returns instance of `LayerDrawable` or `DrawableWrapper` from support library and then do other stuff based on those classes – Selvin Sep 07 '15 at 12:28
  • @Selvin Above codes were working before migrating to API 23! I know I cannot cast but how to solve it? I need to change stars color. – Alex Sep 07 '15 at 12:30
  • question is: do you need this code at all .... it seems like they added ratingbar support in appcompat library ... so maybe it is already using accent color from AppCompat theme – Selvin Sep 07 '15 at 12:32
  • @Selvin I changed to `AppCompatRatingBar` but nothing helped and same error. – Alex Sep 07 '15 at 12:37
  • **question is: do you need this code at all**!!! if they added support for this why are you trying to change it by your own ... comment this code and see what would happend – Selvin Sep 07 '15 at 12:37
  • @Selvin Sorry I didn't understand you. Can you please give me an example of changing those stars color? Thanks. – Alex Sep 07 '15 at 12:39
  • 3
    `DrawableCompat.setTint(ratingBar.getProgressDrawable(), color)` – Selvin Sep 07 '15 at 16:58
  • @Selvin Thank you so much. That worked like a charm. Please send your comment as an answer. Thanks. – Alex Sep 07 '15 at 17:14

2 Answers2

3

DrawableCompat.setTint(ratingBar.getProgressDrawable(),color); by Selvin in the comment section is the correct answer.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Manny265
  • 1,709
  • 4
  • 23
  • 42
0

See https://stackoverflow.com/a/38207513/570168

tl;dr:

 layerDrawable = (LayerDrawable) rb.getProgressDrawable().getWrappedDrawable();
Community
  • 1
  • 1
Tobias
  • 7,282
  • 6
  • 63
  • 85