21 July 2014

Make a Gallery of images using ImageSwitcher

We are going to make an interesting GUI component in Android . You people have become bored of ImageView and ImageButtons, their boring looks and all .Lets try a new concept to display images .
What do we need ?
  • XML layout (activity_main.xml)
  • Gallery
  • ImageSwitcher
  • A java Class (MainActivity.java)
  • Attributes file (attrs.xml) 
  • Any number of images of your choice (I choose 3)
What are we going to do ?
-> We will make a gallery of Images which will display each and every images you have included one by one .     in animated format .

Step 1 : Make a layout with a Gallery and ImageSwitcher and (TextView - optional).(activity_main.xml) .
See to it that the id's of Gallery and ImageSwitcher are to be remembered .

main
The code for activity_main.xml is given below .

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" >
        
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Image switches one by one"/>
         
        <Gallery
            android:id="@+id/galleryimg"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/> 

       
        <ImageSwitcher
            android:id="@+id/switcherimg"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_alignParentLeft="true"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            />
            
    </LinearLayout>

Step 2 : We make an attribute file in res -> values folder . Right Click on values under res folder and Select New -> Android XML File from your Packege Explorer .
new xml

Step 3 : Give name as attrs.xml to the file and Click Finish .
attrs

Step 4 : Copy the code below in attrs.xml .

attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="Gallery1">
        <attr name="android:galleryItemBackground" />
    </declare-styleable>    
</resources>

Step 5 : Include three images in res ->. drawable_hdpi folder .Include images as shown below .
drag image

Select Copy files and press OK . Also drag other two images the same way . Name all the three images as pic1 , pic2 and pic3 .
copy files

Step 6 : Make a class in src folder or use existing (MainActivity.java) . The code for the class is given below .

MainActivity.java
package com.mia.imagegallery;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;

@SuppressWarnings("deprecation")
public class MainActivity extends Activity implements ViewFactory {

    Integer[] imageIDs = {
            R.drawable.pic1,
            R.drawable.pic2,
            R.drawable.pic3
            };
    
    private ImageSwitcher imageSwitcher2;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        imageSwitcher2 = (ImageSwitcher) findViewById(R.id.switcherimg);
        imageSwitcher2.setFactory(this);
        imageSwitcher2.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_in));
        imageSwitcher2.setOutAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_out));
        Gallery gallery = (Gallery) findViewById(R.id.galleryimg);
        gallery.setAdapter(new ImageAdapter(this));
        gallery.setOnItemClickListener(new OnItemClickListener()
        {
            public void onItemClick(AdapterView<?> parent,View v, int position,long id)
            {
                imageSwitcher2.setImageResource(imageIDs[position]);
            }
        });
        
    }

    @Override
    public View makeView() {
        // TODO Auto-generated method stub
        ImageView imageView = new ImageView(this);
        imageView.setBackgroundColor(0xFF000000);
        imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        imageView.setLayoutParams(new 
                ImageSwitcher.LayoutParams(
                    LayoutParams.FILL_PARENT,
                    LayoutParams.FILL_PARENT
                    ));
        return imageView;
    }

   public class ImageAdapter extends BaseAdapter
   {
       private Context context;
       private int itemBackground;
       
       public ImageAdapter(Context c)
       {
          context = c;
           TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
           itemBackground = a.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 0);
           a.recycle();
       }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return imageIDs.length;
    }
    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }
    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        ImageView imageView = new ImageView(context);
        imageView.setImageResource(imageIDs[position]);
        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        imageView.setLayoutParams(new Gallery.LayoutParams(150, 120));
        imageView.setBackgroundResource(itemBackground);
        return imageView;
    }
       
   }
        
}

Step 7 :Run the Project.

Explanation of the code :
  • We define the layout in activity_main.xml which contains Gallery and ImageSwitcher .The Gallery and ImageSwitcher contains the GUI for switching images one by one by default .
  • We change the default ids for Gallery and ImageSwitcher so that we can use them in our class .
<Gallery
       android:id="@+id/galleryimg"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content"/> \      
         <ImageSwitcher
                android:id="@+id/switcherimg"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_alignParentLeft="true"
                android:layout_alignParentBottom="true"
                android:layout_alignParentRight="true"
                />
  • We define the style of our gallery using styleable attribute in file attrs.xml as a resource .
<declare-styleable name="Gallery1">
        <attr name="android:galleryItemBackground" />
    </declare-styleable>  
  • Our class MainActivity extends Activity and implements interface ViewFactory . ViewFactory creates dynamic view of the gallery .
public class MainActivity extends Activity implements ViewFactory
  • Then we make Integer array of the id of images from R.java .
Integer[] imageIDs = {
            R.drawable.pic1,
            R.drawable.pic2,
            R.drawable.pic3
            };
  • We make an instance of ImageSwitcher which we connect it to ImageSwitcher in activity_main.xml with is as switcherimg .
imageSwitcher2 = (ImageSwitcher) findViewById(R.id.switcherimg);
imageSwitcher2.setFactory(this);
  • setOutAnimation and setInAnimation will change the views with animation aspects .
imageSwitcher2.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_in));
        imageSwitcher2.setOutAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_out));
  • All other methods are self explanatory .

Stay tuned with Made In Android

Previous Page Next Page Home

No comments:

Post a Comment

Top