Android RatingBar Example
A Rating Bar is used to show rating in Stars.The user can touch/drag or use arrow keys to set the rating when using the default size RatingBar.
RatingBar Example.
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#C2C2A3">
<RatingBar
android:id="@+id/ratingBar1"
android:layout_marginTop="50dp"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="OK" />
</LinearLayout>
How to change the Number of Stars
Use android:numStars attribute to set the number of stars you want.
MainActivity.java
public class MainActivity extends Activity
{
RatingBar ratingBar;
Button btn;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ratingBar=(RatingBar)findViewById(R.id.ratingBar1);
btn=(Button)findViewById(R.id.button1);
// Set ChangeListener to Rating Bar
ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
Toast.makeText(getApplicationContext(),"Your Selected Ratings : " + String.valueOf(rating),Toast.LENGTH_LONG).show();
}
});
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
float rating=ratingBar.getRating();
Toast.makeText(getApplicationContext(),"Your Selected Ratings : " + String.valueOf(rating),Toast.LENGTH_LONG).show();
}
});
}
}
How to Set The Rating at Run time
use method
use method
ratingBar.setRating(4); or pass any number like 3.5, 4.5 etc.
No comments :
Post a Comment