Android RatingBar Example. Android RatingBar can be used to display a Rating bar containing 5 stars which can be used to display rating or set rating out of 5.
Step 1: Create a new project with name ratingbarexample and package name com.myexample.myratingbar. Select File -> New -> New Project. Fill the forms and click “Finish” button.
Step 2: Open res -> layout -> xml (or) main.xml and add following code. Here we will create a RatingBar and a TextView in a LinearLayout.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <RatingBar android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/ratingbar1"/> <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="0.0" android:id="@+id/textview1" android:textSize="18sp"/> </LinearLayout>
Step 3: Open app -> java -> package and open MainActivity.java. Add following code in it. Here when the rating of RatingBar is changed, we will display the rating in the TextView.
package com.myexample.myratingbar; import android.app.*; import android.os.*; import android.widget.*; import android.widget.RatingBar.*; public class MainActivity extends Activity { RatingBar ratingbar1; TextView textview1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ratingbar1 = findViewById(R.id.ratingbar1); textview1 = findViewById(R.id.textview1); ratingbar1.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener(){ @Override public void onRatingChanged(RatingBar p1, float p2, boolean p3){ textview1.setText(String.valueOf(p2)); } }); } }
Output:
Now run the app. When you change the rating on the RatingBar, the TextView will display the rating.