How to make RatingBar to show five stars

2019-01-16 17:25发布

I am following the standard example of how to add a RatingBar. To control the number of stars I tried to use android:numStars="5". The problem is that the number of stars doesn't seem to do anything at all. In portrait-layout I get 6 stars and when I flip the phone I get about 10 stars. I tried to set the number of stars in my Activity (myBar.setNumStars(5)) that loads the xml but there was no success with that option either.

So my question is how do I define my layout so that it will only show five stars? Set numStars doesn't seem to work.

Thanks in advance, Roland

16条回答
放荡不羁爱自由
2楼-- · 2019-01-16 17:53
<LinearLayout 
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <RatingBar
        android:id="@+id/ruleRatingBar"
        android:isIndicator="true"
        android:numStars="5"
        android:stepSize="0.5"
        style="?android:attr/ratingBarStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</LinearLayout>
查看更多
戒情不戒烟
3楼-- · 2019-01-16 17:54

To show a simple star rating in round figure just use this code

public static String getIntToStar(int starCount) {
        String fillStar = "\u2605";
        String blankStar = "\u2606";
        String star = "";

        for (int i = 0; i < starCount; i++) {
            star = star.concat(" " + fillStar);
        }
        for (int j = (5 - starCount); j > 0; j--) {
            star = star.concat(" " + blankStar);
        }
        return star;
    }

And use it like this

button.setText(getIntToStar(4));

查看更多
何必那么认真
4楼-- · 2019-01-16 17:57

The RatingBar.setNumStar documentation says:

Sets the number of stars to show. In order for these to be shown properly, it is recommended the layout width of this widget be wrap content.

So setting the layout width to wrap_content should solve this problem.

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-01-16 17:57

I'm also facing the problem that exceeding the stars than specified no of stars. For this, we don't want worry about whatever the layout type either relative or linear layout. Simply use the width as follows:

ratingBar.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));


Please avoid using match_parent and fill_parent for ratingbar.
Hope the things would be helpful.

查看更多
我命由我不由天
6楼-- · 2019-01-16 17:58

If you are using

android:layout_width="match_parent"

Use wrap_content and it will only show the set numStars :)

android:layout_width="wrap_content"

查看更多
SAY GOODBYE
7楼-- · 2019-01-16 17:59

The default value is set with andoid:rating in the xml layout.

查看更多
登录 后发表回答