How to create simple RatingBar? - ANDROID - Helper

Monday, October 22, 2018

How to create simple RatingBar?


In this tutorial, We are going to create a simple RatingBar example. First, drag and drop a RatingBar to the layout XML file.

If you want to limit the number of stars then set android:numStars="5"

If you wish to set the default rating then set android:rating="0"

That is it. Your layout XML file will be look as below.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="10dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <RatingBar
            android:id="@+id/ratingBar"
            style="?android:attr/ratingBarStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:numStars="5"
            android:rating="0" />

    </RelativeLayout>

</android.support.constraint.ConstraintLayout>

Use setOnRatingBarChangeListener event to listen the changed rating value.

To get the current rating, Use getRating() method in the RatingBar object.

Your Activity file will be look as below.

MainActivity.java
package com.androidhelper.demo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RatingBar;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RatingBar ratingBar = (RatingBar) findViewById(R.id.ratingBar);
        ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            public void onRatingChanged(RatingBar ratingBar, float rating,
                                        boolean fromUser) {

                // TODO Auto-generated method stub
                Toast.makeText(MainActivity.this, "Rating : " + ratingBar.getRating(), Toast.LENGTH_LONG).show();

            }
        });
    }
}

Youtube Video


1 comment: