Saturday, 21 July 2012

Android Rating Bar Tutorial


Introduction of Android Rating Bar


Situation : We are using android application and we want to rate this.

For this purpose android provide rating bar control.
How to listen rating bar
  • First get the instance of rating bar.
     ratingBar = (RatingBar) findViewById(R.id.ratingBar);
     
  • Then apply the rating change listener for this rating bar.
     ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
      public void onRatingChanged(RatingBar ratingBar, float rating,boolean fromUser) {
      
       write your code
      
      }
     });
     
     
Example to display rating by user
  1. Make layout file(main.xml) which contains a button. If we click on button it change to screen2.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
     
        <RatingBar
            android:id="@+id/ratingBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:numStars="4"
            android:stepSize="1.0"
            android:rating="2.0" />
     
    </LinearLayout>
    
  2. Then apply setOnRatingBarChangeListener

    public class mainactivity extends Activity {
     
     private RatingBar ratingBar;
     
     @Override
     public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      addListenerOnRatingBar();
     }
     
      public void addListenerOnRatingBar() {
     
     ratingBar = (RatingBar) findViewById(R.id.ratingBar);
     ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
      public void onRatingChanged(RatingBar ratingBar, float rating,boolean fromUser) {
     
          Toast.makeText(MyAndroidAppActivity.this,
           String.valueOf(rating), Toast.LENGTH_SHORT).show();
     
      }
     });
     
    }
    
    
  3. Output : 


            

No comments:

Post a Comment