logo

RatingBar

In Android, you can use “android.widget.RatingBar” to display rating bar component in stars icon. The user is able to touch, drag or click on the stars to set the rating value easily.

In this tutorial, we show you how to use XML to display a rating bar. When user click on the rating bar’s star, the selected rating value will be displayed as a toasted message.

layout file contains:

<?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" >
 
    <TextView
        android:id="@+id/lblRateMe"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Rate Me" />
 
    <RatingBar
        android:id="@+id/ratingBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="5"
        android:stepSize="1.0"
        android:rating="0.0" />
 
 </LinearLayout>
 

Activity class implements

the class RatingBar.OnRatingBarChangeListener i.e.

public class UIActivity extends Activity implements RatingBar.OnRatingBarChangeListener

Register the setOnRatingBarChangeListener(), so that we get notified in method onRatingChanged().


rate=(RatingBar)findViewById(R.id.ratingBar);// create RatingBar object
rate.setOnRatingBarChangeListener(this);

Display ratings by implementing abstract method onRatingChanged of OnRatingBarChangeListener


			public void onRatingChanged(RatingBar ratingBar,float rating, boolean fromUser){
				
				Toast.makeText(UIActivity.this,"Rating is : "+rating,Toast.LENGTH_SHORT).show();
				
			}      

SeekBar

The SeekBar is a slider with a maximum value with which you can select values from a range visually. The range of the seek bar is from 0 to the maximum value. We can set the maximum value using android:max attribute in layout file.

Layout file contains:

<?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" >
 
 	<TextView 
		android:layout_width="fill_parent"
		android:layout_height="wrap_content" 
		android:text="Seekbar"/>
 
    <SeekBar android:id="@+id/seekbar"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:max="100"
		android:minWidth="250px"  />

	<TextView android:id="@+id/textview"
		android:layout_width="fill_parent"
		android:layout_height="wrap_content" />
 
</LinearLayout>
 

Our tutorial displays the changing value of the SeekBar as you drag it.
The SeekBar has three states: drag start, changing and drag ended.

package com.mobisys.android.ui_components;

import android.app.Activity;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;


	public class UIActivity extends Activity
	{
		SeekBar seek;
		TextView value;
	
		public void onCreate(Bundle savedInstanceState)
		{
				super.onCreate(savedInstanceState);
		        setContentView(R.layout.main);
			 
		        seek=(SeekBar)findViewById(R.id.seekbar);
		        value=(TextView)findViewById(R.id.textview);
		        seek.setOnSeekBarChangeListener(new OnSeekBarChangeListener(){
                       //drag change
					@Override
					public void onProgressChanged(SeekBar seekBar, int process,
							boolean fromUser) {
						
						value.setText("SeekBar Value is: "+process);
						Toast.makeText(UIActivity.this, "changing", Toast.LENGTH_LONG).show();
					}
                               // drag start
					@Override
					public void onStartTrackingTouch(SeekBar seekBar) {
						
						Toast.makeText(UIActivity.this, "starting to track touch", Toast.LENGTH_LONG).show();
					}
                                 // Drag stop
					@Override
					public void onStopTrackingTouch(SeekBar seekBar) {
						
						Toast.makeText(UIActivity.this, "Ended tracking touch", Toast.LENGTH_LONG).show();
					}
		        	
		        });
		}

	      
	}

Method for drag start: runs when you first touch the bar.

Method for changing: this one gets executed as you drag the bar

Method for drag stop: runs when you let go of the bar

Gallery

A Gallery is a View commonly used to display items in a horizontally scrolling list that locks the current selection at the center.

layout file contains:

<?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" >
 
<Gallery
    android:id="@+id/Gallery01"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
</Gallery>

<ImageView android:id="@+id/ImageView01"
    android:layout_marginTop="8dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"></ImageView>
 
</LinearLayout>
 

It also has an ImageView element which is used to show the selected Image in a larger ImageView. Here is how it would look when executed.

Now, in our Activity,we created small sized images of antartica and stored them in the res/drawable folder starting form antartica1.png to antartica10.png.

we create an array of these resources/images in our activity with the following code:

Integer[] pics = {
R.drawable.antartica1,
R.drawable.antartica2,
R.drawable.antartica3,
R.drawable.antartica4,
R.drawable.antartica5,
R.drawable.antartica6,
R.drawable.antartica7,
R.drawable.antartica8,
R.drawable.antartica9,
R.drawable.antartica10
};

As we have seen with all the other views so far, we need to have an adapter that associates the view with the data. Here the view is Gallery and the data is the above mentioned 10 images. An Adapter plays the role of linking the two as shown below:


Gallery ga = (Gallery)findViewById(R.id.Gallery01);
ga.setAdapter(new ImageAdapter(this));

Now we will create our own implementation of ImageAdapter extending the BaseAdapter class.The moment we extend the BaseAdapter, we have to override 4 methods. They are getCount(), getItem(), getItemId() and getView().

Let us see the constructor of the ImageAdpater:

public class ImageAdapter extends BaseAdapter {
			
		    int mGalleryItemBackground;
		    private Context ctx;

		   
		    public ImageAdapter(Context c) {
		        ctx = c;
		       
		        TypedArray ta = c.obtainStyledAttributes(R.styleable.Gallery1);
		        mGalleryItemBackground = ta.getResourceId(
		                R.styleable.Gallery1_android_galleryItemBackground, 1);
		        ta.recycle();
		    }

It takes the context that is passed to the constructor. We need to examine this code a little. First, we can define our own resources or attributes in an XML file. Those attributes can be retrieved through the method obtainStyledAttributes. This is a method on the Context object. The returned value needs to be stored in a TypedArray object. A TypedArray is nothing but a container for an array of values that are returned by obtainStyledAttributes.

So, here we have created an xml file by name attributes.xml in the res/values folder with the following content:

<resources>
     <declare-styleable name="Gallery1">
    <attr name="android:galleryItemBackground"/>
     </declare-styleable>
</resources>

Here Gallery1 is a custom name for a style defined by us. In this style, we are trying to say what should be the background of our images. For that we are using a pre-defined backgournd in R.attr class as galleryItemBackground.

So, this is accessed in the ImageAdapter contructor through the line.

ta.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 1);
ta.recycle();

The number 1 is to say that it is the first element in the attributes.xml file under the styelable.Gallery1.

The rest of the overridden methods are:

@Override
public int getCount() {
    return pics.length;
}


@Override
public Object getItem(int pos) {
    return pos;
}

@Override
public long getItemId(int pos) {
    return pos;
}


@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
    ImageView iv = new ImageView(ctx);
    iv.setImageResource(pics[arg0]);
    iv.setScaleType(ImageView.ScaleType.FIT_XY);
    iv.setLayoutParams(new Gallery.LayoutParams(150,120));
    iv.setBackgroundResource(mGalleryItemBackground);
    return iv;
}

The getView actually returns a View object when called. Here we have overridden it to return a ImageView object with the selected image inside it with some scale, layout paramaters and the image background set.

Finally in the onCreate() method of the activity we have captured the onClick event on a Gallery item and within that we have toasted a message as well as displayed the image.

ga.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
    Toast.makeText(UIActivity.this, "You have selected picture " + (pos+1) + " of Antartica",
        Toast.LENGTH_SHORT).show();
    imageView.setImageResource(pics[pos]);
}
});

Download Source code

Click here to download

AUTHOR: Vikas Hiran
No Comments

Leave a Comment

Your email address will not be published.