Android RatingBar: getProgressDrawable doesn't cast to right Class

后端 未结 5 1096
耶瑟儿~
耶瑟儿~ 2021-01-21 06:37

I am using

Android RatingBar change star colors

This line of code

    LayerDrawable stars = (LayerDrawable) rating_bar.getProgressDrawable();
         


        
5条回答
  •  爱一瞬间的悲伤
    2021-01-21 06:58

    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);
    }
    

提交回复
热议问题