android rating bar example
Hello Guys. Welcome to our new tutorial of android rating bar example using android studio. android ratingbar is used to get rating from any user. Here we will teach you how to use android rating bar. user simple drag or click on the star for set ratting value. please follow the code given below to display android rating bar in android.
- First Create a new project in Android Studio
- File ⇒ New Android ⇒ Application Project
- Then Open src -> package -> MainActivity.java and then add following code :
JAVA (MainActivity.java)
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.RatingBar;
import android.view.View;
import android.widget.TextView;
public class Rating extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rating);
MobileAds.initialize(this,getString(R.string.admob_app_id));
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
rBar = (RatingBar) findViewById(R.id.ratingBar1);
tView = (TextView) findViewById(R.id.textview111);
btn = (Button)findViewById(R.id.btnGet);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int noofstars = rBar.getNumStars();
float getrating = rBar.getRating();
tView.setText("Rating: "+getrating+"/"+noofstars);
}
});
}
}
XML (activity_main.xml)
<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">
<RatingBar
android:id="@+id/ratingBar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:numStars="5"
android:rating="3.5"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btnGet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/ratingBar1"
android:layout_below="@+id/ratingBar1"
android:layout_marginTop="16dp"
android:text="Get Rating"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/ratingBar1" />
<TextView
android:id="@+id/textview111"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/btnGet"
android:layout_below="@+id/btnGet"
android:layout_marginTop="20dp"
android:textSize="20dp"
android:textStyle="bold"/>
</android.support.constraint.ConstraintLayout>


