Saturday, May 16, 2015

How to use RatingBar in Android

Table of contents
  1. Android RatingBar Example
    • setOnRatingBarChangeListener()
    • onRatingChanged()
    • isIndicator
    • numStars
    • rating
    • stepSize

1. Android RatingBar Example

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    android:background="#ffffff"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25dp"
        android:text="Give us a rating..."
        />
    <!--
        ***************** RatingBar ********************
        android:isIndicator Whether this rating bar is an indicator (and non-changeable by the user).
        android:numStars The number of stars (or rating items) to show.
        android:rating  The rating to set by default.
        android:stepSize The step size of the rating.
    -->
    <RatingBar
        android:id="@+id/rb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:isIndicator="false"
        android:numStars="5"
        android:rating="0"
        android:stepSize="0.5"
        android:layout_below="@id/tv"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
import android.widget.RatingBar;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Get the widgets reference from XML layout
        final TextView tv = (TextView) findViewById(R.id.tv);
        RatingBar rb = (RatingBar) findViewById(R.id.rb);

        //Set TextView text color
        tv.setTextColor(Color.parseColor("#FFB91BFF"));

        rb.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
                tv.setText("Your Rating : " + rating);
            }
        });
    }
}
More android examples