Monday, September 2, 2013

How to play saved video in android?


  • Create android project named "savedVideoView".
  • Now create 'raw' folder in 'res' directory.Note: Do not change the folder name.
  • Add Video file (mp4) which you want to play in application.
  • Now just add following code in activity_main.xml file 

activity_main.xml



<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:minWidth="854dip"
    android:minHeight="480dip"
    >
<VideoView android:id="@+id/welcome"
android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center"
    android:fitsSystemWindows="true"
    android:minWidth="854dip"
    android:minHeight="480dip"
    >
</VideoView>
</LinearLayout>



  • Add following code in MainActivity.java file.

MainActivity.java



public class MainActivity extends Activity 
{

VideoView vv;

@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
// it is used to set full screen video
    requestWindowFeature(Window.FEATURE_NO_TITLE);  
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,   
                                WindowManager.LayoutParams.FLAG_FULLSCREEN);  

    setContentView(R.layout.play_intro);
    vv = (VideoView) findViewById(R.id.welcome);

       
    MediaController mc = new MediaController(this); 
    vv.setMediaController(mc); 
    mc.hide();
          // Here resource is 'video2' video file which is stored in 'raw' directory 
    vv.setVideoURI(Uri.parse("android.resource://com.tumbi/"+R.raw.video2));
   
    vv.start();
   
    vv.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
   
    @Override
    public void onCompletion(MediaPlayer mp) 
    {
    onPause();
                         // After completion of video it goes to CompleteVideoActivity automatically
    Intent i=new Intent(MainActivity.this,CompleteVideoActivity.class);
    startActivity(i);
    android.os.Process.killProcess(android.os.Process.myPid());
    }
    });
   
}

public void onPause ()
{
super.onPause();
vv.stopPlayback();
}
}

  • Done ! Now run the Project and get the O/P.

how to play youtube video in videoview android ?


how to play youtube video in videoview android ?

You can play youtube video in your application.There is no need to add third party library or other API.


  • First of all create one android project named "VideoViewTube".
  • You need to add VideoView component in your xml file.Open activity_main.xml and add following code:

activity_main.xml



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center"
    android:minWidth="854dip"
    android:minHeight="480dip"
    >

    <VideoView
        android:id="@+id/videoView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:fitsSystemWindows="true"
        android:minHeight="480dip"
        android:minWidth="854dip" />

</LinearLayout>


  • If your internet speed is low then It will take some time to play youtube video,Between buffering time and playing time your application UI may freeze.
  • To resolve this issue use Async Task (AsyncTask Tutorial).
  • Open MainActivity.java file and create MyAsyncTask class in below onCreate() method. 
  • MyAsyncTask class extends AsyncTask<Void,Void,Void>,Write following code in MyAsyncTask class.


private class YourAsyncTask extends AsyncTask<Void, Void, Void>
    {
        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(MainActivity.this, "", "Loading Video wait...", true);
        }

        @Override
        protected Void doInBackground(Void... params)
        {
            try
            {
                String url = "http://www.youtube.com/watch?v=OtLa7wDpuOU";
                videoUrl = getUrlVideoRTSP(url);
                Log.e("Video url for playing=========>>>>>", videoUrl);
            }
            catch (Exception e)
            {
                Log.e("Login Soap Calling in Exception", e.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result)
        {
            super.onPostExecute(result);
            progressDialog.dismiss();
        
            videoView.setVideoURI(Uri.parse(videoUrl));
            MediaController mc = new MediaController(MainActivity.this);
            videoView.setMediaController(mc);
            videoView.requestFocus();
            videoView.start();          
            mc.show();
        }

    }


  •  Now you get one error in  getUrlVideoRTSP(url).It is because youtube video is RTSP type videos RTSP means Real Time Streaming Protocol.We need to get Video URL from RTSP.
  • Add following two methods below MyAsyncTask class. getUrlVideoRTSP(String urlYoutube); and extractYoutubeId(String url);  


public static String getUrlVideoRTSP(String urlYoutube)
    {
        try
        {
            String gdy = "http://gdata.youtube.com/feeds/api/videos/";
            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            String id = extractYoutubeId(urlYoutube);
            URL url = new URL(gdy + id);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            Document doc = documentBuilder.parse(connection.getInputStream());
            Element el = doc.getDocumentElement();
            NodeList list = el.getElementsByTagName("media:content");///media:content
            String cursor = urlYoutube;
            for (int i = 0; i < list.getLength(); i++)
            {
                Node node = list.item(i);
                if (node != null)
                {
                    NamedNodeMap nodeMap = node.getAttributes();
                    HashMap<String, String> maps = new HashMap<String, String>();
                    for (int j = 0; j < nodeMap.getLength(); j++)
                    {
                        Attr att = (Attr) nodeMap.item(j);
                        maps.put(att.getName(), att.getValue());
                    }
                    if (maps.containsKey("yt:format"))
                    {
                        String f = maps.get("yt:format");
                        if (maps.containsKey("url"))
                        {
                            cursor = maps.get("url");
                        }
                        if (f.equals("1"))
                            return cursor;
                    }
                }
            }
            return cursor;
        }
        catch (Exception ex)
        {
            Log.e("Get Url Video RTSP Exception======>>", ex.toString());
        }
        return urlYoutube;

    }

protected static String extractYoutubeId(String url) throws MalformedURLException    {        String id = null;
        try
        {
            String query = new URL(url).getQuery();
            if (query != null)
            {
                String[] param = query.split("&");
                for (String row : param)
                {
                    String[] param1 = row.split("=");
                    if (param1[0].equals("v"))
                    {
                        id = param1[1];
                    }
                }
            }
            else
            {
                if (url.contains("embed"))
                {
                    id = url.substring(url.lastIndexOf("/") + 1);
                }
            }
        }
        catch (Exception ex)
        {
            Log.e("Exception", ex.toString());
        }
        return id;
    }


  • Now just define VideoView and call AsyncTask Class in onCreate() Method.

MainActivity.java


public class MainActivity extends Activity {
VideoView videoView;
String videoUrl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoView = (VideoView)findViewById(R.id.videoView);
new YourAsyncTask().execute();
}


  • At last write onPause method in bottom of MainActivity.java class
public void onPause ()
{
super.onPause();
videoView.stopPlayback();
}


The Completed MainActivity.java Class is : Part 2

Get Full Suorce Code: Here



VideoView Part2


MainActivity.Java


package com.example.videoview;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends Activity {

VideoView videoView;
String videoUrl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);  
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,   
                                WindowManager.LayoutParams.FLAG_FULLSCREEN);  
setContentView(R.layout.activity_main);
videoView = (VideoView)findViewById(R.id.videoView);
/* String SrcPath = "rtsp://v5.cache1.c.youtube.com/CjYLENy73wIaLQnhycnrJQ8qmRMYESARFEIJbXYtZ29vZ2xlSARSBXdhdGNoYPj_hYjnq6uUTQw=/0/0/0/video.3gp";

videoView.setVideoURI(Uri.parse(SrcPath));
      videoView.setMediaController(new MediaController(this));
      videoView.requestFocus();
      videoView.start();*/
new YourAsyncTask().execute();
}

private class YourAsyncTask extends AsyncTask<Void, Void, Void>
    {
        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute()
        {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(MainActivity.this, "", "Loading Video wait...", true);
        }

        @Override
        protected Void doInBackground(Void... params)
        {
            try
            {
                String url = "http://www.youtube.com/watch?v=OtLa7wDpuOU";
                videoUrl = getUrlVideoRTSP(url);
                Log.e("Video url for playing=========>>>>>", videoUrl);
            }
            catch (Exception e)
            {
                Log.e("Login Soap Calling in Exception", e.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result)
        {
            super.onPostExecute(result);
            progressDialog.dismiss();
/*
            videoView.setVideoURI(Uri.parse("rtsp://v4.cache1.c.youtube.com/CiILENy73wIaGQk4RDShYkdS1BMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp"));
            videoView.setMediaController(new MediaController(AlertDetail.this));
            videoView.requestFocus();
            videoView.start();*/            
            videoView.setVideoURI(Uri.parse(videoUrl));
            MediaController mc = new MediaController(MainActivity.this);
            videoView.setMediaController(mc);
            videoView.requestFocus();
            videoView.start();          
            mc.show();
        }

    }

public static String getUrlVideoRTSP(String urlYoutube)
    {
        try
        {
            String gdy = "http://gdata.youtube.com/feeds/api/videos/";
            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            String id = extractYoutubeId(urlYoutube);
            URL url = new URL(gdy + id);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            Document doc = documentBuilder.parse(connection.getInputStream());
            Element el = doc.getDocumentElement();
            NodeList list = el.getElementsByTagName("media:content");///media:content
            String cursor = urlYoutube;
            for (int i = 0; i < list.getLength(); i++)
            {
                Node node = list.item(i);
                if (node != null)
                {
                    NamedNodeMap nodeMap = node.getAttributes();
                    HashMap<String, String> maps = new HashMap<String, String>();
                    for (int j = 0; j < nodeMap.getLength(); j++)
                    {
                        Attr att = (Attr) nodeMap.item(j);
                        maps.put(att.getName(), att.getValue());
                    }
                    if (maps.containsKey("yt:format"))
                    {
                        String f = maps.get("yt:format");
                        if (maps.containsKey("url"))
                        {
                            cursor = maps.get("url");
                        }
                        if (f.equals("1"))
                            return cursor;
                    }
                }
            }
            return cursor;
        }
        catch (Exception ex)
        {
            Log.e("Get Url Video RTSP Exception======>>", ex.toString());
        }
        return urlYoutube;

    }

protected static String extractYoutubeId(String url) throws MalformedURLException
    {
        String id = null;
        try
        {
            String query = new URL(url).getQuery();
            if (query != null)
            {
                String[] param = query.split("&");
                for (String row : param)
                {
                    String[] param1 = row.split("=");
                    if (param1[0].equals("v"))
                    {
                        id = param1[1];
                    }
                }
            }
            else
            {
                if (url.contains("embed"))
                {
                    id = url.substring(url.lastIndexOf("/") + 1);
                }
            }
        }
        catch (Exception ex)
        {
            Log.e("Exception", ex.toString());
        }
        return id;
    }
public void onPause ()
{
super.onPause();
videoView.stopPlayback();
}
}


Get Full Source Code: Here


Play sound in android example

You can play sound file in your android application.You need MP3 file which you want to play.
Here is full description and only one method you need to apply in your code.


  • First create folder in res named raw.Copy MP3 file in it (in raw folder).
  • Generate MediaPlayer Object in Activity class.Make the changes as shown in BOLD.


                                    public class MainActivity extends Activity {

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


  • Create one method playSound() in your activity class and add following code:

               
 
                 private void playSound() {
mp = MediaPlayer.create(MultiActivity.this, R.raw.sound_file);
        mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.release();
}
});
mp.start();
}


  • Add setOnClickListener() method of button and only call this playSound() method.
            
                 playButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
playSound();
}
});


  • For Big MP3 file you can create one button to stop sound.Just put mp.release(); and mp.stop(); code in it.
      •  

Sunday, September 1, 2013

GridView Example


GridView is a 2 - Dimensional display of your content. It is mainly useful to show icons or images.
Take a look of GridView.



Example:
  • First Create project named "GridView_Example".
  • Download some images/photos you would like to set in GridView and save it in res/drawable/ directory.
  • Open activity_main.xml file and add following code:

activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/gridview"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:columnWidth="90dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
/>


  • Open the MainActivity.java file and add following code:

MainActivity.java



public void onCreate(Bundle savedInstanceState) 
{
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

   GridView gridview = (GridView) findViewById(R.id.gridview);
   gridview.setAdapter(new ImageAdapter(this));

   gridview.setOnItemClickListener(new OnItemClickListener() {
       public void onItemClick(AdapterView<?> parent, View v, int position, long id) 
       {
           Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show();
       }
   });
}


  • Now You get some error in MainActivity.java file,but ignore it.Create New Class file (File - New - Class) named it ImageAdapter.java.
  • Insert following code in ImageAdapter.java file. 

ImageAdapter.java



public class ImageAdapter extends BaseAdapter
{
private Context mContext;

    public ImageAdapter(Context c) 
    {
        mContext = c;
    }

    public int getCount() 
    {
        return mThumbIds.length;
    }

    public Object getItem(int position) 
    {
        return null;
    }

    public long getItemId(int position) 
    {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) 
    {
        ImageView imageView;
        if (convertView == null) 
        {  // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } 
        else 
        {
            imageView = (ImageView) convertView;
        }

        imageView.setImageResource(mThumbIds[position]);
        return imageView;
    }

    // references to our images
    private Integer[] mThumbIds = {
            R.drawable.cat, R.drawable.dog,
            R.drawable.cat_two, R.drawable.dog_two,
            R.drawable.dog_three, R.drawable.doglast,
            R.drawable.cat, R.drawable.dog,
            R.drawable.cat_two, R.drawable.dog_two,
            R.drawable.dog_three, R.drawable.doglast,
            R.drawable.cat, R.drawable.dog,
            R.drawable.cat_two, R.drawable.dog_two,
            R.drawable.dog_three, R.drawable.doglast,
            R.drawable.cat, R.drawable.dog,
            R.drawable.cat_two, R.drawable.dog_two,
            R.drawable.dog_three, R.drawable.doglast,
    };

}

  • Note that, here you have to change names in mThumbIds integer array as per your image names.
  • Done, Now run the project and get output like above image.  


Monday, August 26, 2013

Custom ListView Example

This is a tutorial about customizing listview with and image and text.

Download Source Code for FREE:Here


Creating New Project

  • Create New Project in Eclipse. File => New Project.
  • Create New folder in res named drawable.
  • Create New gradient_bg.xml file in drawable directory and fill with following code. It is used to set gradient background in listView.

gradient_bg.xml


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <gradient
      android:startColor="#424242"
      android:centerColor="#585858"
      android:endColor="#6E6E6E"
      android:angle="270" />
</shape>


  • Create New gradient_bg_hover.xml file in drawable directory and fill with following code. It is used to set gradient background when listView item is pressed.

 gradient_bg_hover.xml


<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
  <gradient
      android:startColor="#8A0808"
      android:centerColor="#610B0B"
      android:endColor="#B40404"
      android:angle="270" />
</shape>

  • Create New list_main.xml file in drawable directory and fill with following code. It is used to integrate above files into listView..

list_main.xml


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
     android:state_selected="false"
        android:state_pressed="false"
        android:drawable="@drawable/gradient_bg" />
    <item android:state_pressed="true"
        android:drawable="@drawable/gradient_bg_hover" />
    <item android:state_selected="true"
     android:state_pressed="false"
        android:drawable="@drawable/gradient_bg_hover" />
</selector>

  • Now add following code into activity_main.xml file.

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <ListView
        android:id="@+id/listView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:divider="#2A0A12"
        android:dividerHeight="2dp"
        android:listSelector="@drawable/list_main" />
</LinearLayout>

  • Next step is to design single row of listView. Create New xml file in layout directory and name it as row_layout.xml.

row_layout.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/list_main"
    android:orientation="horizontal"
    android:padding="5dip" >


    <LinearLayout
        android:id="@+id/thumbnail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="5dip"
        android:padding="3dip" >

        <ImageView
            android:id="@+id/list_image"
            android:layout_width="50dip"
            android:layout_height="50dip"
            android:src="@drawable/ic_launcher" />
    </LinearLayout>

   

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/thumbnail"
        android:text="Country name"
        android:textColor="#FFFFFF"
        android:textSize="15dip"
        android:textStyle="bold"
        android:typeface="sans" />

</RelativeLayout>

  • Until now we completed designing part of the listView. Next step is to add content in listview with different images. Add following code in MainActivity.java file. 

MainActivity.java



public class MainActivity extends Activity {


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

String listArray[] = new String[] { "India", "England", "Canada",
"New zealand", "South Africa", "Pakistan", "West indies" };
int icon[] = new int[] { R.drawable.india, R.drawable.england,
R.drawable.canada, R.drawable.new_zealand,
R.drawable.south_africa, R.drawable.pakistan,
R.drawable.west_indies };

ListView listView = (ListView) findViewById(R.id.listView);
List<HashMap<String, String>> aList = new ArrayList<HashMap<String, String>>();

for (int i = 0; i <= listArray.length - 1; i++) {

HashMap<String, String> hm = new HashMap<String, String>();
hm.put("title", listArray[i]);
hm.put("icon", Integer.toString(icon[i]));
aList.add(hm);
}

String[] sfrm = { "title", "icon" };
int[] sto = { R.id.title, R.id.list_image };

SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList,
R.layout.row_layout, sfrm, sto);

listView.setAdapter(adapter);

listView.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View view,
int position, long id) {

switch (position) {

case 0:
Toast.makeText(getApplicationContext(), "India",
Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(getApplicationContext(), "England",
Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(getApplicationContext(), "Canada",
Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(getApplicationContext(), "New zealand",
Toast.LENGTH_SHORT).show();
break;
case 4:
Toast.makeText(getApplicationContext(), "South Africa",
Toast.LENGTH_SHORT).show();
break;
case 5:
Toast.makeText(getApplicationContext(), "Pakistan",
Toast.LENGTH_SHORT).show();
break;
case 6:
Toast.makeText(getApplicationContext(), "West Indies",
Toast.LENGTH_SHORT).show();
break;

}

}
});
}
}

  • Done !

Download Source Code for FREE:Here



Wednesday, August 21, 2013

Rating Bar Full Example

activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    
    <RatingBar android:id="@+id/rating_1"
    android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="3"
        android:rating="2.5">
    </RatingBar>
    
    <RatingBar android:id="@+id/rating_2"
    android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="5"
        android:rating="2.25">
    </RatingBar>
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip">
    
<TextView  
android:id="@+id/rating"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
   
    <RatingBar android:id="@+id/small_ratingbar"
            style="?android:attr/ratingBarStyleSmall"
            android:layout_marginLeft="5dip"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical" />
    </LinearLayout>
    
    <RatingBar android:id="@+id/indicator_ratingbar"
        style="?android:attr/ratingBarStyleIndicator"
        android:layout_marginLeft="5dip"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical" 
        />
        
</LinearLayout>



MainActivity.java



public class MainActivity extends Activity implements RatingBar.OnRatingBarChangeListener
{
RatingBar mSmallRatingBar;
RatingBar mIndicatingRatingBar;
TextView mRatingText;
    /** Called when the activity is first created. */
   
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        mRatingText=(TextView)findViewById(R.id.rating);
        
        mSmallRatingBar=(RatingBar)findViewById(R.id.small_ratingbar);
        mIndicatingRatingBar=(RatingBar)findViewById(R.id.indicator_ratingbar);
        
        ((RatingBar)findViewById(R.id.rating_1)).setOnRatingBarChangeListener(this);
        ((RatingBar)findViewById(R.id.rating_2)).setOnRatingBarChangeListener(this);
    }
    
   
    public void onRatingChanged(RatingBar ratingBar,float rating,boolean fromTouch)
    {
    final int numStars=ratingBar.getNumStars();
   
    mRatingText.setText(getString(R.string.ratingbar_rating)+" "+rating+" / "+numStars);
   
    if(mIndicatingRatingBar.getNumStars()!=numStars)
    {
    mIndicatingRatingBar.setNumStars(numStars);
    mSmallRatingBar.setNumStars(numStars);
    }
   
    if(mIndicatingRatingBar.getRating()!=rating)
    {
    mIndicatingRatingBar.setRating(rating);
    mSmallRatingBar.setRating(rating);
    }
   
    final float ratingBarStepSize=ratingBar.getStepSize();
   
    if(mIndicatingRatingBar.getStepSize()!=ratingBarStepSize)
    {
    mIndicatingRatingBar.setStepSize(ratingBarStepSize);
    mSmallRatingBar.setStepSize(ratingBarStepSize);
    }
    }

}