Android Rating Bar Example
Rating Bar is a widget in Android which is used to rate application or website or anything which you want to rate. In this tutorial, we will learn on how to use rating bars in our Android Activity with an example.
Please follow the steps below to add Rating Bar in your Android Activity:
1) There is the widget called Rating Bar in the palette please drag and drop this Rating Bar in your activity and you will be able to use it.
2) Now, there are some properties you can change for this Rating Bar.
- First property you may be interested in is the number of stars you want to show. So once you double click on this Rating Bar, first property comes here is the NumStars which is number of stars, for example, you want to rate out of five stars, so we will give the maximum number of stars,
- Second property is the initial rating of the star, for example, you want to show initial rating of 2 on your star bar or rating star bar, and
- And third property is the Step size that means how many steps you want to increase in your stars once you hover over it.
- Keep the fourth property as a default.
3) Now take a large text box and a button in the activity, and change the text of the button as Submit.
Java Coding For Rating Bar
And now we are ready to write the code for this Rating Bar. We will create two methods, one which will listen on this star click event, or you can say the rating event and one which will listen to the button click event.
1) So now first, go to the MainActivity.java file and declare three variables, first for the button, second for Rating Bar and third for the text box.
2) After declaring the variables now we are going to write a method for the button or the listener for Rating Bar and cast the Rating Bar and the text box in this method.
3) Now we are going to take RatingBar variable call setOnRatingBarChangeListener on it.
4) And now copy the method which is Listener for Rating Bar and paste it in your onCreate method and run the program.
5) Now our app is running, so for example, if we change the rating to four, we will see the rating gets changed to four. So in this way you can prepare the listener for Rating Bar change.
6) Now we will use the button to collect the rating and display it in the form of a toast on message and in order to do it we have to make another method and cast the rating bar and the button as shown below
7) Now we will set the On Click Listener for thus button variable and create a Toast or message along with the three arguments.
8) Now paste this method to On Create method.
9) And now re-run the application. When we click the Submit button the rating will also display in the form of message
So in this way you can use Rating Bar in your Android Activity.