I find myself a little baffled here. I’m fairly new to android/java development so please help out here to identify what I’m doing wrong. I have checked aggressively throughout google, android dev and stack but couldn’t find much info on this.
I have a string variable with a number as theRating. e.g. 2.5 (out of 10)
I am trying to display this using ratingbarstylesmall… It’s for showing only and not rating.
RatingBar rb = new RatingBar(this, null, android.R.attr.ratingBarStyleSmall);
rb.setIsIndicator(true);
rb.setNumStars(5);
rb.setStepSize((float) 0.5);
rb.setMax(10);
rb.setRating(Integer.parseInt(theRating));
llTextEtc.addView(rb);
The stars load fine inside LienarLayout (llTextEtc), show up in the right place, it’s the right style stars that i want (small) but…
it’s completely random. Some show 8 stars, some show 15 then back to 7 and so on. Totally random. What am I doing wrong?
Thanks guys
Update:
With help from the accepted answer:
A LinearLayout was added to hold the ratingbar with wrap_content layout. Otherwise the parent (scrollview) became wrap_content.
LinearLayout llRating = new LinearLayout(this);
RatingBar rb = new RatingBar(this, null, android.R.attr.ratingBarStyleSmall);
rb.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
rb.setIsIndicator(true);
rb.setNumStars(5);
rb.setRating(Float.parseFloat(theRating)/2);
llRating.addView(rb);
llTextEtc.addView(llRating);
setStepSize and setMax was also removed, Rating was set to float instead of integer. The stars are calculated and then set. stepSize and Max doesn’t help when isIndicator is true.
I noticed a couple of problems here. First and most important you need to set the layout width to WRAP_CONTENT for it to work properly. The following is from the dev guide:
The number of stars set (via setNumStars(int) or in an XML layout) will be shown when the layout width is set to wrap content (if another layout width is set, the results may be unpredictable).Secondly I noticed that you have set the
stepSizeto afloatand you are seting the rating using anInterger. I would first convert the value from the URL feed to aFloatand then validate it before passing it to the rating bar.