Android RatingBar is an extension of ProgressBar and SeekBar that shows rating as stars. User can touch/drag or use arrow keys to set the rating when using the default size RatingBar.
The smaller RatingBar style ( ratingBarStyleSmall) and the larger indicator-only style (ratingBarStyleIndicator) doesn't support user interaction and it can be used as indicators only.
In this tutorial, we are going to discuss following things:
Android RatingBar simple usage in xml layout is given below:
android:rating attribute of Android RatingBar specify rating value that will be shown selected. To set the rating of Android RatingBar in xml layout, set the android:rating attribute of Android RatingBar as follows:
We can also set the rating of an Android RatingBar programmatically as follows:
Rating of an Android RatingBar can have float value.
android:numStars attribute of Android RatingBar specify number of stars that will be shown in Android RatingBar. To set the number of starts in Android RatingBar, we can set the android:numStars attribute of Android RatingBar in xml layout as follows:
We can also change the numStarts of an Android RatingBar programmatically as follows:
android:numStarscan have only integer value.
android:stepSize of Android Rating specify the step size of the android ratingBar. We can set the stepSize of an Android RatingBar as follows:
android:stepSize can have float value.
We can get the rating value of an Android RatingBar on runtime as follows:
android:isIndicator attribute of Android RatingBar specify whether this rating bar is an indicator. An indicator are non changable by the user.
We can customize Android RatingBar by defining style under res -> values ->styles.xml as follows:
Next step is to use it in your Android RatingBar as follows:
To handle onRatingChanged event of Android RatingBar implement RatingBar.OnRatingBarChangeListener in main activity class, and override onRatingChanged method.
In this example, We discussed different aspect of Android RatingBar. Now lets implement the demo for Android RatingBar
Step 1: Create a new project in Android Studio and name it Android RatingBar.
Step 2: Open res -> values ->colors.xml and replace its code with below given code:
Step 3: Open res -> values ->styles.xml and replace its code with below given code:
Step 4: Open res -> layout -> activity_main.xml and add following code
Step 5: Open your MainActivity.java and replace its source with source of my MainActivity.java as follows:
Step 6: Clean and run the project to see the result.