articles

Home / DeveloperSection / Articles / Rating Bar control in Android

Rating Bar control in Android

Chris Anderson 13503 24-Oct-2011

In this article I am going to explain how to create rating bar control in an android application by using RatingBar widget. When a user click on the rating bar, a new rating will be displayed by the toast message.

·         Start a new project, named RatingBarDemo.

·         Open res/layout/main.xml and add a RatingBar widget inside the linear layout.

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="vertical"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent">
     <RatingBar android:id="@+id/ratingbar"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:numStars="5"
                  android:stepSize="1.0" />
</LinearLayout>

·         Now we have to show the new rating to the user by using toast message. To do this add the following code in the activity:

import android.app.Activity;

import android.os.Bundle;
import android.widget.RatingBar;
import android.widget.Toast;
import android.widget.RatingBar.OnRatingBarChangeListener;

public class RatingBarActivity extends Activity {

     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
         final RatingBar ratingbar = (RatingBar) findViewById(R.id.ratingbar);
         ratingbar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {

                      public void onRatingChanged(RatingBar ratingBar, float rating,
                                                                boolean fromUser) {

                           Toast.makeText(RatingBarActivity.this, "New Rating:
                                            "
                                           "+rating, Toast.LENGTH_SHORT).show();
                     }
              });
    }
}

The above code captures the RatingBar widget from the layout with findViewById(int) and then sets an RatingBar.OnRatingBarChangeListener. The onRatingChanged()callback method then defines the action to perform when the user sets a rating. In this case, a simple Toast message displays the new rating.

·         Run the application

You output look something like this:

Rating Bar control in Android

When users select a new rating, a rating will be displayed in the toast message.



Updated 07-Sep-2019
hi I am software developer at mindstick software pvt. ltd.

Leave Comment

Comments

Liked By