Sunday, 27 January 2013

RatingBar Example in Android

activity_main.xml:

<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" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="22dp"
        android:layout_marginTop="14dp"
        android:text="Give us rating"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <RatingBar
        android:id="@+id/ratingBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1" />

    <Button
        android:id="@+id/showRating"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/ratingBar1"
        android:layout_below="@+id/ratingBar1"
        android:layout_marginLeft="56dp"
        android:layout_marginTop="18dp"
        android:text="Show Rating" />

</RelativeLayout>

MainActivity.java:
package com.ratingbar.inspire.ram;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.Toast;

public class MainActivity extends Activity {
float ratingByUser;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

RatingBar ratinbar = (RatingBar) findViewById(R.id.ratingBar1);
ratinbar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {

@Override
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromUser) {
// TODO Auto-generated method stub
ratingByUser = rating;

}
});
Button displayRating = (Button) findViewById(R.id.showRating);
displayRating.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"rating is:" + ratingByUser, 3000).show();
}
});
}

}