Introduction
Android RatingBar can be used to get a rating from the user. The Rating returns a floating-point number. It may be 2.0, 3.5, 4.0 etc. Android RatingBar displays the rating in stars. In this article, I will show you how to create a RatingBar Android App using Android Studio.
Requirements
Important Points to Remember
The getRating() method of Android RatingBar class returns the rating number.
Create New Project
Open Android Studio and create a New Android Studio Project.
activity_main.xml
Drag the RatingBar and Button from the palette now the activity_main.xml file will look like this,
- <RelativeLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- tools:context=".MainActivity" >
-
- <RatingBar
- android:id="@+id/ratingBar1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentTop="true"
- android:layout_centerHorizontal="true"
- android:layout_marginTop="44dp" />
-
- <Button
- android:id="@+id/button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignLeft="@+id/ratingBar1"
- android:layout_below="@+id/ratingBar1"
- android:layout_marginLeft="92dp"
- android:layout_marginTop="66dp"
- android:text="submit" />
-
- </RelativeLayout>
Activity class
Let's write the code to display the rating of the user.
MainActivity.java
The Header File
- package abu.ratingbar;
-
- import android.os.Bundle;
- import android.app.Activity;
- import android.view.Menu;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- import android.widget.RatingBar;
- import android.widget.Toast;
Declare the Button with Rating Bar,
- public class MainActivity extends Activity {
- RatingBar ratingbar1;
- Button button;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- addListenerOnButtonClick();
- }
-
- public void addListenerOnButtonClick(){
- ratingbar1=(RatingBar)findViewById(R.id.ratingBar1);
- button=(Button)findViewById(R.id.button1);
-
- button.setOnClickListener(new OnClickListener(){
-
- @Override
- public void onClick(View arg0) String rating=String.valueOf(ratingbar1.getRating());
- Toast.makeText(getApplicationContext(), rating, Toast.LENGTH_LONG).show();
- }
-
- });
- }
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
-
- getMenuInflater().inflate(R.menu.activity_main, menu);
- return true;
- }
-
- }
Debug The Error
Now, go to the menu bar and click make project or press ctrl+f9 to debug the error.
Run the project
Then click Run button or press shift+f10 To run the project. And choose the virtual machine and click OK.
Output
We have successfully created a RatingBar Android application using Android Studio.