Ilias Tsagklis

About Ilias Tsagklis

Ilias Tsagklis is a senior software engineer working in the telecom domain. He is an applications developer in a wide variety of applications/services. Ilias is co-founder and Executive Editor at Java Code Geeks.

Android Rating Bar Example

In Android it’s very easy to accept user rating using a Rating Bar. In this tutorial we are going to see how to set up and display a Rating Bar with Stars. When the user slides over the  bar, the rating goes up or down by one Star and the selected/deselected Stars change color automatically as does the value of the rating. 
 
 
 
 
 
 
 
For this tutorial, we will use the following tools in a Windows 64-bit platform:

  1. JDK 1.7
  2. Eclipse 4.2 Juno
  3. Android SKD 4.2

1. Create a new Android Project

Open Eclipse IDE and go to File -> New -> Project -> Android -> Android Application Project. You have to specify the Application Name, the Project Name and the Package name in the appropriate text fields and then click Next.

In the next window make sure the “Create activity” option is selected in order to create a new activity for your project, and click Next. This is optional as you can create a new activity after creating the project, but you can do it all in one step.

Select “BlankActivity” and click Next.

You will be asked to specify some information about the new activity.  In the Layout Name text field you have to specify the name of the file that will contain the layout description of your app. In our case the file res/layout/main.xml will be created. Then, click Finish.

2. Adding resources

Use the Package Explorer in Eclipse to navigate to res/values/strings.xml

When you open the strings.xml file, Eclipse will display the graphical Resources View editor :

That’s a nice and easy tool you can use to add several resources to your application like strings, integers, color values etc. But we are going to use the traditional way and that is editing the strings.xml file by hand. In the bottom of the screen, press the string.xml tab and paste the following code :

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

    <string name="app_name">AndroidRatingBar</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="text_label_1">Rate</string>
    <string name="button_label">Submit</string>
    <string name="text_label_2">Result: </string>
</resources>

So, we’ve just created some string resources that we can use in many ways and in many places in our app.

3. Creating a Rating Bar

Open res/layout/main.xml file :

And paste the following code :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/lblRateMe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/text_label_1"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <RatingBar
        android:id="@+id/ratingBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="4"
        android:stepSize="1.0"
        android:rating="2.0" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_label" />

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/lblResult"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/text_label_2"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <TextView
            android:id="@+id/txtRatingValue"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=""
            android:textAppearance="?android:attr/textAppearanceSmall" />

    </LinearLayout>

</LinearLayout>

In the code of the RatingBar notice the android:numStars="4", android:stepSize="1.0" and android:rating="2.0" attributes. The android:numStars="4" attribute states that the RatingBar will consist of 4 Stars. The android:stepSize="1.0" is a very important attribute because it dictates that the amount of rate increase or decrease will be 1.0. That means that when the user slides over the bar, the Stars will be selected on deselected one at a time. For example, if that attribute had a value of 0.5, the rating would increase/decrease by 0.5, which would mean that when the user slides over the bar, half a star will be selected or deselected. The android:rating="2.0" set the default value of the rating at 2.0, which means 2 Stars will be selected by default. Now you may open the Graphical layout editor to preview the User Interface you created:

4. Adding a ClickListener to the Button and an OnRatingBarChangeListener to the Rating Bar

Go to the java file that contains the code of the activity you’ve just created and paste the following code:

package com.javacodegeeks.android.androidratingbarexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

  private RatingBar ratingBar;
  private TextView ratingValue;
  private Button button;

  @Override
  public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.main);

	addListenerOnRatingBar();
	addListenerOnButton();

  }

  public void addListenerOnRatingBar() {

	ratingBar = (RatingBar) findViewById(R.id.ratingBar);
	ratingValue = (TextView) findViewById(R.id.txtRatingValue);

	ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {

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

			ratingValue.setText(String.valueOf(rating));

		}
	});
  }

  public void addListenerOnButton() {

	ratingBar = (RatingBar) findViewById(R.id.ratingBar);
	button = (Button) findViewById(R.id.button);

	button.setOnClickListener(new OnClickListener() {

		@Override
		public void onClick(View v) {

			Toast.makeText(MainActivity.this, String.valueOf(ratingBar.getRating()), Toast.LENGTH_LONG).show();
		}

	});

  }
}

As you can see we introduce two listeners in our application. The OnRatingBarChangeListener monitors the state of the Rating Bar. Every time the value of the Rating Bar changes, the onRatingChanged function is executed and changes the values of the “Result”.

5. Run the application

This is the main screen of our Application. You can see that the rating is 2 Stars by default:

Now, slide your pointer over the Rating Bar and notice the “Result” value change. As you will see the ratings goes up or down by one Star each time you slide over the Rating Bar:

And when you press the Button:

Download Eclipse Project

This was an Android Rating Bar Example. Download the Eclipse Project of this tutorial: AndroidRatingBarExample.zip

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close