Android RatingBar setRating doesn't work

MasterCrumble picture MasterCrumble · Nov 18, 2012 · Viewed 7.8k times · Source

I am trying to display an int value as a ratingBar. The max value is 5.

This is my XML file:

<RatingBar
            android:id="@+id/ratBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:isIndicator="false"
            android:numStars="5" />

But if I set the rating with setRating(), android draws a lot of stars. I can't figure out how many because my screen is too small.

Could anybody tell me what's wrong?

Answer

Alpay picture Alpay · Jan 4, 2013

I couldn' t understand what exactly your problem is, but using RatingBar in Android applications is quite easy anyway. You need to define your RatingBar in a proper location;

<RatingBar
        android:id="@+id/ratingBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:isIndicator="true"
        android:max="5"
        android:numStars="3" />

get a reference to it, within your activity;

private RatingBar rb;
...
this.rb = (RatingBar) findViewById(R.id.ratingBar1);

and start to set values to fill the stars;

this.rb.setRating(2); , this.rb.setRating((float)2.5); etc.

If your screen is too small to display five stars, you can set the number of stars, just as I did above. And you have several options;

1) You can put two ratingbars one under the other one with 3 and the other with 2 stars. When your number exceeds 3, you can continue filling the 2 stars of the bottom ratingbar.

2) If possible, you can set float values instead of integers. So that you can set 1, 1.5, 2, 2.5, 3, 3.5, etc. and you can fill 3 stars for your interval 1-5 after a little algebra.