In today’s Android SDK tutorial I will show you how to use the rating bar widget.
The Result
Let’s make a widget that displays in text the number of stars you selected from a rating. Like always be sure to change your android:minSdkVersion to a corresponding version.
Motorola Xoom: Android rating bar, 3 stars selected
Now if we touch on another star:
Android star rating, 7 stars selected
The Manifest (AndroidManifest.xml)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.helloandroid"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="13" />
<application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">
<activity android:name=".HelloAndroid"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The Layout (main.xml)
<?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"> <TextView android:id="@+id/ratingText" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <RatingBar android:id="@+id/rating" android:isIndicator="false" android:stepSize="1.0" android:numStars="10" android:rating="0.0" android:layout_width="wrap_content" android:layout_height="wrap_content"> </RatingBar> </LinearLayout>
The Rating Bar Java Class(HelloAndroid.java)
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.widget.RatingBar;
import android.widget.TextView;
public class HelloAndroid extends Activity implements RatingBar.OnRatingBarChangeListener{
RatingBar rating; // declare RatingBar object
TextView ratingText;// declare TextView Object
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState); // call super class constructor
setContentView(R.layout.main);// set content from main.xml
ratingText=(TextView)findViewById(R.id.ratingText);// create TextView object
rating=(RatingBar)findViewById(R.id.rating);// create RatingBar object
rating.setOnRatingBarChangeListener(this);// select listener to be HelloAndroid (this) class
}
// implement abstract method onRatingChanged
public void onRatingChanged(RatingBar ratingBar,float rating, boolean fromUser){
ratingText.setText(""+this.rating.getRating()); // display rating as number in TextView, use "this.rating" to not confuse with "float rating"
}
}