android set part of the stars in the rating bar if the value is in decimal places

StackOverflow https://stackoverflow.com/questions/18662058

  •  28-06-2022
  •  | 
  •  

سؤال

I would like to show the user's score using the ratingbar. For example, if the user gets 7 out of 30 questions correct, the textview (tv_percentage) shows correctly for 23.33%, yet the rating star, which should then show 1.17 stars out of 5 stars, yet now is that whatever the score is, is always showing 5 stars.

What have I done wrong for the following?

Code:

    SharedPreferences score = this.getSharedPreferences("MyApp", 0);
    int userscore = score.getInt("score", 0);
    int userQnumber = score.getInt("number_of_question_to_selected", 9999);     

    double scoring100 = Double.valueOf(userscore) / Double.valueOf(userQnumber) *100;
    String stripped2 = Double.valueOf(scoring100).toString();       
    DecimalFormat myFormatter1 = new DecimalFormat("###,###,###.##");       

    stripped2 = myFormatter1.format(Double.valueOf(stripped2));     
    tv_percentage.setText(""+stripped2+"%");        

    ratingBar1.setRating(Float.parseFloat(stripped2)); 

editted code:

    float d= (float) (scoring100 /100 * 5);
    String S = Double.valueOf(d).toString();    
    tv2_90.setText(""+S); // for testing only, tv2_90 showing proper value
    ratingBar1.setStepSize((d));
    ratingBar1.setRating(Float.parseFloat(stripped2)); 

Layout:

            <RatingBar
                android:id="@+id/ratingBar1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:isIndicator="true"
                android:max="100"
                android:numStars="5"
                android:stepSize="0.1" />
هل كانت مفيدة؟

المحلول

You can find it here:

    float d= (float) ((number*5) /100);
    RatingBar rb = (RatingBar) findViewById(R.id.ratingBar1);
    rb.setRating(d);

And on your layout:

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

نصائح أخرى

If you want to show rating in exact points you need to set stepSize in

rate.setStepSize((float) 0.1);
rate.setRating((float)3.6);

It will show Fourth star be filled more than half.

Via XML

<RatingBar
 .....
 android:max="5"
 android:numStars="5"
 android:progressTint="@color/golden"
 android:rating="2"
 android:stepSize="1"/>

Via Java Code

  ratingBar.setMax(5);
  ratingBar.setNumStars(5);
  ratingBar.setStepSize(0.1f);

Wait.. there's more

You'll have to set width attribute of your RatingBar to wrap_content otherwise the above mentioned attributes won't have an effect on the UI.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top