Create a simple example of using a RatingBar in Android. In this example, we'll create an Android app with a RatingBar, and the user can set the rating using the RatingBar. We'll also display a toast message with the selected rating.
There Are Some Common Attributes for RatingBar:
id | This ID serves as the control's unique identity. |
layout_width | match_parent -> Text area contains fullscreen wrap_content-> Text area contains only text size |
layout_width | match_parent -> Text area contains fullscreen wrap_content-> Text area contains only text size |
numStars | 5 -> How many stars contain in rating bar |
stepSize | 1 -> Every stars value 1 |
Step 1:
File open res/layout/activity_main.xml file −:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_margin="20dp"
android:orientation="vertical">
<RatingBar
android:id="@+id/ratingBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:numStars="5"
android:stepSize="1.0" />
<TextView
android:id="@+id/ratingText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/ratingBar"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:text="Selected Rating: 0.0" />
</LinearLayout>
</RelativeLayout>
Step 2:
File open com.microappvalley.newtestproject/MainActivity.kt file −
package com.microappvalley.newtestproject
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import android.widget.RatingBar
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var ratingBar: RatingBar
lateinit var ratingText: TextView
@SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
ratingBar= findViewById(R.id.ratingBar)
ratingText=findViewById(R.id.ratingText)
ratingBar.setOnRatingBarChangeListener { _, rating, fromUser ->
// Display a toast message with the selected rating
if (fromUser) {
ratingText.text="Selected Rating: $rating"
Toast.makeText(this, "Selected Rating: $rating", Toast.LENGTH_SHORT).show()
}
}
}
}
Open Device Manager, run the emulator, and then run the application. Next, check the working output and check the output you declared in your code.