To get the rating from the user, the RatingBar is used in Android which is a subclass of the AbsSeekBar class and returns a floating-point number such as 2.0, 3.5, 4.0, etc. The rating is displayed in stars by the Android RatingBar. The RatingBar class in Android have the getRating() method to return the rating number.
Android RatingBar Example:
activity_main.xml:
In the activity_main.xml file, drag the RatingBar and Button from the pallet.
<?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"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="rate" android:id="@+id/button" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="0.615" /> <RatingBar android:id="@+id/ratingBar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="72dp" android:layout_marginTop="60dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout> |
Activity class:(File: MainActivity.java)
In the MainActivity.java file, we will write the code to display the rating of the user.
package com.example.radioapp; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.RatingBar; import android.widget.Toast; public class MainActivity extends AppCompatActivity { RatingBar ratingbar; Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); addListenerOnButtonClick(); } public void addListenerOnButtonClick(){ ratingbar=(RatingBar)findViewById(R.id.ratingBar); button=(Button)findViewById(R.id.button); //Performing action on Button Click button.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View arg0) { //Getting the rating and displaying it on the toast String rating=String.valueOf(ratingbar.getRating()); Toast.makeText(getApplicationContext(), rating, Toast.LENGTH_LONG).show(); } }); } } |
Output 1:
Output 2: