RatingBar android - 自定义绘制运行时

RatingBar android - custom draw runtime

我在列表中显示了评级栏。

随着人们对项目的评分从 1 星到 4 星 - 评分栏应该改变星星的颜色或背景或覆盖物或其他象征变化的东西(组织中的客户要求用于使用颜色来识别状态, 例如绿色 = 好)

我在想改变星星的颜色就可以解决这个问题。但是,大多数解决方案都围绕着更改评分栏中使用的默认图形,而不是如何在用户更改评级后进行所有者绘制。

我想你正在寻找色调:

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

运行起来不是很顺利,但应该是一个入手点。

此外,您可以在触摸侦听器中设置色调 - 我想这样对您来说会更好:

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