Thursday 27 February 2014

How to Create RatingBar in Android

main.xml

<LinearLayout 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"
    android:orientation="vertical">

    <TextView
        android:id="@+id/tv_ratingBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Rating Bar"
        android:textColor="#336633"
        android:textSize="18sp"
        android:textStyle="bold"
        android:layout_marginTop="20dp"
        android:layout_gravity="center" />
<RatingBar
    android:id="@+id/ratingBar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:layout_gravity="center"
    android:numStars="5"/>
</LinearLayout>






RatingBarActivity.java

package com.rakesh.tiwari.ratingbar;

import android.app.Activity;
import android.os.Bundle;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;

public class RatingBarActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

    RatingBar ratingBar=(RatingBar)findViewById(R.id.ratingBar);
    final TextView tv_ratingBar=(TextView)findViewById(R.id.tv_ratingBar);
    ratingBar.setRating((float)2);
    ratingBar.setStepSize((float)0.3);
    ratingBar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
       
        @Override
        public void onRatingChanged(RatingBar ratingBar, float rating,
                boolean fromUser) {
            // TODO Auto-generated method stub
        tv_ratingBar.setText(String.valueOf(rating));   
        }
    });
    }

}



AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.rakesh.tiwari.ratingbar"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:screenOrientation="portrait"
            android:name="com.rakesh.tiwari.ratingbar.RatingBarActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>








No comments:

Post a Comment