Home » Android » Android RatingBar (filling next star)

Android RatingBar (filling next star)

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have the following RatingBar:

<RatingBar
                android:id="@+id/ratingBar"
                android:layout_width="wrap_content"
                android:layout_height="35dp"
                android:numStars="5"
                android:max="5"
                android:stepSize="1.0"
                android:layout_marginTop="12dp"/>

When I press the left part of a star – it is selected, but when I press the right part – the following star is selected. I need the star I click on to be selected whichever part of it I click.
Help me please to understand what is wrong.

How to&Answers:

It is perhaps an unfortunate side effect of RatingBar extending ProgressBar, which internally uses a int progress with rounding (rather than ceil) to go from a float seek position to a int progress. The best solution I have found is to set your stepSize to 0.01 rather then 1, then set

rb.setOnRatingBarChangeListener( new RatingBar.OnRatingBarChangeListener() {
    @Override
    public void onRatingChanged( final RatingBar ratingBar, final float rating, final boolean fromUser ) {
        if ( fromUser ) {
            ratingBar.setRating( Math.ceil(rating) );
        }
    }
});