I am using
Android RatingBar change star colors
This line of code
LayerDrawable stars = (LayerDrawable) rating_bar.getProgressDrawable();
>
Came accross the same issue today when creating a RatingBar programmatically. The following workaround is working for me also on Android 4.x devices using the AppCompatRatingBar:
AppCompatRatingBar rb = new AppCompatRatingBar(activity);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.gravity = Gravity.CENTER;
rb.setLayoutParams(layoutParams);
rb.setStepSize(1.0f);
rb.setMax(5);
LayerDrawable layerDrawable = null;
if (rb.getProgressDrawable() instanceof LayerDrawable) {
layerDrawable = (LayerDrawable) rb.getProgressDrawable();
} else if (rb.getProgressDrawable() instanceof DrawableWrapper) {
DrawableWrapper wrapper = (DrawableWrapper) rb.getProgressDrawable();
if (wrapper.getWrappedDrawable() instanceof LayerDrawable) {
layerDrawable = (LayerDrawable) wrapper.getWrappedDrawable();
}
}
if (layerDrawable != null) {
layerDrawable.getDrawable(2).setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
layerDrawable.getDrawable(0).setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
layerDrawable.getDrawable(1).setColorFilter(ContextCompat.getColor(activity, R.color.primary), PorterDuff.Mode.SRC_ATOP);
}