Android Custom Gallery Example

android.widget.Gallery is subclass of AbsSpinner. It displays items in horizontal direction. This example will show you how to use android.widget.Gallery and ImageSwitcher to implement an android image gallery application.

1. android.widget.Gallery Properties And Methods.

  1. android:unselectedAlpha : Sets the transparency of the unselected list item.
  2. android:spacing : Sets the horizontal spacing between gallery items.
  3. setOnItemSelectedListener() : Set a listener to listen gallery item select event.
  4. setOnItemClickListener() : Set a listener to listen gallery item click event.

2. Steps To Use android.widget.Gallery

  1. Create a BaseAdapter object.
  2. Override it’s getView() method, this method will return a View object which will be shown in the gallery selected item.
  3. Get the Gallery object and set the data adapter to it.
  4. Set an OnItemSelectedListener object to response when gallery item is  selected.
  5. Set an OnItemClickListener object to response when gallery item is  clicked.

3. Android Gallery Example.

This example will use a Gallery and an ImageSwitcher widget. When user select a gallery item, it’s image will be displayed in bottom ImageSwitcher widget and scale to half size of original image.

When user click gallery item, the item image  will be rotated 360 degree.

If you can not watch the above video, you can see it on the youtube URL https://youtu.be/AwBjEDrlR0o

activity_gallery.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Gallery
        android:id="@+id/galleryExample"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:spacing="5pt"
        android:unselectedAlpha="0.6"
        android:layout_marginTop="35pt"/>

    <ImageSwitcher
        android:id="@+id/galleryImageSwitcher"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"/>

</LinearLayout>

GalleryActivity.java

package com.dev2qa.example;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;

public class GalleryActivity extends AppCompatActivity {

    // Image resource id array.
    private int[] imageDrawableIdArr = {R.drawable.red_apple_256_256, R.drawable.fireman_car_256_256, R.drawable.great_britain_256_256};

    // This handler will rotate the image.
    private Handler galleryImageHalder;

    //This message means rotate image.
    private int MSG_ROTATE_IMAGE = 1;

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

        setTitle("dev2qa.com --- Android Gallery Example");

        // This ImageSwitcher will be used to scale the gallery selected image.
        final ImageSwitcher galleryImageSwitcher = (ImageSwitcher)findViewById(R.id.galleryImageSwitcher);
        galleryImageSwitcher.setInAnimation(GalleryActivity.this, android.R.anim.fade_in);
        galleryImageSwitcher.setOutAnimation(GalleryActivity.this, android.R.anim.fade_out);

        // Set ImageSwitcher ViewFactory, this factory will return the ImageView object which will be displayed.
        galleryImageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
            @Override
            public View makeView() {
                ImageView imgView = new ImageView(GalleryActivity.this);
                imgView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                ImageSwitcher.LayoutParams imgLayoutParams = new ImageSwitcher.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER_HORIZONTAL);
                imgView.setLayoutParams(imgLayoutParams);
                return imgView;
            }
        });

        // Create a BaseAdapter used by Gallery.
        final BaseAdapter galleryAdapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return imageDrawableIdArr.length;
            }

            @Override
            public Object getItem(int itemIndex) {
                return imageDrawableIdArr[itemIndex];
            }

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

            // This method will return an ImageView that displayed in gallery.
            @Override
            public View getView(int itemIndex, View view, ViewGroup viewGroup) {
                ImageView imageView = new ImageView(GalleryActivity.this);
                imageView.setImageResource(imageDrawableIdArr[itemIndex]);
                return imageView;
            }
        };

        // Get the Gallery object.
        final Gallery imageGallery = (Gallery)findViewById(R.id.galleryExample);
        // Set above data adapter to galerry.
        imageGallery.setAdapter(galleryAdapter);

        // When gallery item is selected then scale image to a bigger one.
        imageGallery.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            // Store previous gallery item image resource index.
            private  int previousItemIndex = -1;

            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int itemIndex, long l) {
                // Get current gallery selected image.
                ImageView currImageView = (ImageView)view;
                // Set above image to gallery switcher object.
                galleryImageSwitcher.setImageDrawable(currImageView.getDrawable());
                // Scale the gallery image switcher.
                ImageView galleryImageSwitcherView = (ImageView)galleryImageSwitcher.getCurrentView();
                this.scaleImageView(galleryImageSwitcherView,0.5f, 0.5f);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }

            /* This method will be used to scale ImageView's image. */
            private void scaleImageView(ImageView selectedItemImageView, float scaleX, float scaleY)
            {
                BitmapDrawable bitmapDrawable = (BitmapDrawable)selectedItemImageView.getDrawable();

                Bitmap originalBitmap = bitmapDrawable.getBitmap();

                int originalWidth = originalBitmap.getWidth();

                int originalHeight = originalBitmap.getHeight();

                Bitmap.Config originalConfig = originalBitmap.getConfig();

                int newWidth = (int)(originalWidth * scaleX);

                int newHeight = (int)(originalHeight * scaleY);

                // Create a bitmap which has scaled width and height value from original bitmap.
                Bitmap scaleBitmap = Bitmap.createBitmap(newWidth, newHeight, originalConfig);

                Canvas scaleCanvas = new Canvas(scaleBitmap);

                Matrix scaleMatrix = new Matrix();

                // Set x y scale value.
                scaleMatrix.setScale(scaleX, scaleY, 0, 0);

                Paint paint = new Paint();
                scaleCanvas.drawBitmap(originalBitmap, scaleMatrix, paint);
                selectedItemImageView.setImageBitmap(scaleBitmap);
            }
        });

        // When gallery item is clicked then rotate the image for 360 degree each second 60 degree.
        imageGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                  // Create a Thread object.
                  Thread rotateImageThread = new Thread(){
                        @Override
                        public void run() {
                            try {
                                for (int i = 0; i < 6; i++) {
                                    // Create a Message.
                                    Message msg = new Message();
                                    msg.what = MSG_ROTATE_IMAGE;
                                    // Send the message to galleryImageHandler to process.
                                    galleryImageHalder.sendMessage(msg);
                                    Thread.sleep(100);
                                }
                            }catch(Exception ex)
                            {
                                ex.printStackTrace();
                            }
                        }
                  };

                  // Start the Thread object.
                  rotateImageThread.start();
            }
        });

        galleryImageHalder = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                // Get gallery selected view object.
                View selectedItemView = imageGallery.getSelectedView();
                ImageView selectedItemImageView = (ImageView)selectedItemView;

                // When receive rotate image message.
                if(msg.what == MSG_ROTATE_IMAGE)
                {
                    // Rotate the selected image 60 degree.
                    this.rotateImage(selectedItemImageView, 60);
                }
            }

            // This method is used to rotate the image for special degree.
            private void rotateImage(ImageView originalImageView, long rotateDegree)
            {
                BitmapDrawable originalBitmapDrawable = (BitmapDrawable)originalImageView.getDrawable();
                Bitmap originalBitmap = originalBitmapDrawable.getBitmap();
                Bitmap.Config originalConfig = originalBitmap.getConfig();
                int originalWidth = originalBitmap.getWidth();
                int originalHeight = originalBitmap.getHeight();

                Bitmap rotateBitmap = Bitmap.createBitmap(originalWidth, originalHeight, originalConfig);

                Canvas rotateCanvas = new Canvas(rotateBitmap);

                Matrix rotateMatrix = new Matrix();

                // Rotate around the center point of the original image.
                rotateMatrix.setRotate(rotateDegree, originalBitmap.getWidth()/2, originalBitmap.getHeight()/2);

                Paint paint = new Paint();
                rotateCanvas.drawBitmap(originalBitmap, rotateMatrix, paint);

                originalImageView.setImageBitmap(rotateBitmap);
            }
        };
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.