Dynamic RatingBar in Kotlin
Android RatingBar is a user interface widget which is used to get the rating from the customers or users. It is an extension of SeekBar and ProgressBar that shows star ratings and it allow users to give the rating by clicking on the stars.
In RatingBar, we can set the step size using android:stepSize and it will always return a rating value as floating point number such as 1.0, 2.0, 2.5 etc. By using, android:numStars attribute we can specify the number of stars in RatingBar. RatingBar is used to get ratings form users or customers about the product, movie or hotel experience etc.
RatingBar can be created manually or programmatically but we are going to discuss programmatically or dynamically.
First we create a new project by following the below steps:
- Click on File, then New => New Project.
- After that include the Kotlin support and click on next.
- Select the minimum SDK as per convenience and click next button.
- Then select the Empty activity => next => finish.
Modify the activity_main.xml file
In this file, we use the LinearLayout and set its attributes like id, padding etc and it can be accessed in the Kotlin file using id.
Add application name in strings.xml file
Here, we can put all the strings which can be used in the application in any file. So, we update the app_name which can be seen on the top of the activity.
Creating RatingBar in MainActivity.kt file
First of all, we declare variable rBar to create RatingBar and set its attributes using it.
val rBar = RatingBar(this) val layoutParams = LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) rBar.layoutParams = layoutParams rBar.stepSize = 1.0.toFloat() rBar.numStars = 5
then, we declare another variable to create a button like this
val button = Button(this) val layoutParams1 = LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) button.text="Submit Rating"
After this, RatingBar and button added into the LinearLayout using the statements
Run as Emulator:
Please Login to comment...