In this tutorial, we will learn how to use RatingBar in Android. RatingBar is used to get the rating from users. User can give rating by clicking on starts. When the user clicks on starts of Ratingbar it returns float value like 2.5, 1.0, 4.5 etc. In this tutorial, we will learn how to add Ratingbar in the XML layout file. How to get Rating in Java file.
Page Contents
First of all, we will write our layout file code. In the layout file, we will add a RatingBar widget and a button. After that, we will write code in Java file to get rating given by the user on button click. Check this XML code.
XML Code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<RatingBar
android:id="@+id/ratingbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:saveEnabled="true"
android:numStars="5"
android:layout_marginBottom="10dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:id="@+id/submit"/>
</LinearLayout>
After writing this code we will write code in our java file to fetch rating given by the user.
Java Code:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final RatingBar ratingBar=findViewById(R.id.ratingbar);
final Button button=findViewById(R.id.submit);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
float rating=ratingBar.getRating();
Toast.makeText(getApplicationContext(),rating+"",Toast.LENGTH_SHORT).show();
}
});
}
}
Output:
Here is the output after writing this code.
Parvesh Sandila is a results-driven tech professional with 8+ years of experience in web and mobile development, leadership, and emerging technologies.
After completing his Master’s in Computer Applications (MCA), he began his journey as a programming mentor, guiding 100+ students and helping them build strong foundations in coding. In 2019, he founded Owlbuddy.com, a platform dedicated to providing free, high-quality programming tutorials for aspiring developers.
He then transitioned into a full-time programmer, where his hands-on expertise and problem-solving skills led him to grow into a Team Lead and Technical Project Manager, successfully delivering scalable web and mobile solutions. Today, he works with advanced technologies such as AI systems, RAG architectures, and modern digital solutions, while also collaborating through a strategic partnership with Technobae (UK) to build next-generation products.
