How to create Custom RatingBar? - ANDROID - Helper

Tuesday, October 23, 2018

How to create Custom RatingBar?




In this tutorial we saw how to create a simple RatingBar. Now we are going to see how to customize it.

Just use progressDrawable. Copy and Paste the star empty and filled icon in the drawable folder.
Then, Create an XML file in the drawable folder. Set the corresponding images in the background, progress and secondaryProgress IDs.

Your file should be same as below.

custom_ratingbar.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@android:id/background"
        android:drawable="@drawable/star_off" />
    <item android:id="@android:id/secondaryProgress"
        android:drawable="@drawable/star_off" />
    <item android:id="@android:id/progress"
        android:drawable="@drawable/star_on" />
</layer-list>

The drawable icons are given below. [star_on.png & star_off.png]


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">
    <LinearLayout
        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:layout_gravity="center"
            android:layout_marginTop="50dp"
            android:numStars="5"
            android:rating="3"
            android:stepSize="0.5" />
        <RatingBar
            android:id="@+id/ratingBarCustom"
            style="?android:attr/ratingBarStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:numStars="5"
            android:progressDrawable="@drawable/custom_ratingbar"
            android:rating="3"
            android:stepSize="0.5" />
    </LinearLayout>
</android.support.constraint.ConstraintLayout>



No comments:

Post a Comment