RatingBar android - custom draw runtime

瘦欲@ 提交于 2019-12-25 04:33:13

问题


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.


回答1:


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.

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



来源:https://stackoverflow.com/questions/36745845/ratingbar-android-custom-draw-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!