Toll Free - 855-572-2777 / 855-572-APPS

Our Thinking

Android Gallery Widget Example and Tutorial

By Pallavi Daga | In Android | on June 28, 2012

One of the Android layout widget – Gallery has lessen the pain of developer when one needs to use horizontally scrolling list specially in case of showing images in gallery view. But sometimes we need to customize this gallery widget as per r

cheap generic priligy

equirement, for example navigating gallery using next-previous buttons which are placed at left and right side of gallery, highlighting selected image with border to make it more user friendly.

Here is code for Gallery Implementation which includes following features :-

1. Horizontal gallery view
2. Showing selected image from gallery in larger view
3. Next-Previous buttons for gallery navigation
4. Highlighting selected image in horizontal gallery view

Next-Previous buttons implementation :-

This can be easily done by maintaining current position of the selected item in gallery view. One needs to increment position when user clicks on right arrow and set gallery selection to that position and needs to decrement position when clicked on left arrow and then set gallery selection.

Highlighting selected item from gallery implementation :-

One can write custom drawable which can be set to background of image view to apply border of gallery image view. Different drawable files can be created and applied to gallery view for its different states like onFocus, onPressed etc.

Code for GalleryDemoActivity.java

package com.gallerydemo;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;

public class GalleryDemoActivity extends Activity {

    private ImageView selectedImageView;

    private ImageView leftArrowImageView;

    private ImageView rightArrowImageView;

    private Gallery gallery;

    private int selectedImagePosition = 0;

    private List<Drawable> drawables;

    private GalleryImageAdapter galImageAdapter;

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

        getDrawablesList();
        setupUI();
    }

    private void setupUI() {

        selectedImageView = (ImageView) findViewById(R.id.selected_imageview);
        leftArrowImageView = (ImageView) findViewById(R.id.left_arrow_imageview);
        rightArrowImageView = (ImageView) findViewById(R.id.right_arrow_imageview);
        gallery = (Gallery) findViewById(R.id.gallery);

        leftArrowImageView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (selectedImagePosition > 0) {
                    --selectedImagePosition;

                }

                gallery.setSelection(selectedImagePosition, false);
            }
        });

        rightArrowImageView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                if (selectedImagePosition < drawables.size() - 1) {
                    ++selectedImagePosition;

                }

                gallery.setSelection(selectedImagePosition, false);

            }
        });

        gallery.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

                selectedImagePosition = pos;

                if (selectedImagePosition > 0 && selectedImagePosition < drawables.size() - 1) {

                    leftArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_left_enabled));
                    rightArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_right_enabled));

                } else if (selectedImagePosition == 0) {

                    leftArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_left_disabled));

                } else if (selectedImagePosition == drawables.size() - 1) {

                    rightArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_right_disabled));
                }

                changeBorderForSelectedImage(selectedImagePosition);
                setSelectedImage(selectedImagePosition);
            }

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

            }

        });

        galImageAdapter = new GalleryImageAdapter(this, drawables);

        gallery.setAdapter(galImageAdapter);

        if (drawables.size() > 0) {

            gallery.setSelection(selectedImagePosition, false);

        }

        if (drawables.size() == 1) {

            rightArrowImageView.setImageDrawable(getResources().getDrawable(R.drawable.arrow_right_disabled));
        }

    }

    private void changeBorderForSelectedImage(int selectedItemPos) {

        int count = gallery.getChildCount();

        for (int i = 0; i < count; i++) {

            ImageView imageView = (ImageView) gallery.getChildAt(i);
            imageView.setBackgroundDrawable(getResources().getDrawable(R.drawable.image_border));
            imageView.setPadding(3, 3, 3, 3);

        }

        ImageView imageView = (ImageView) gallery.getSelectedView();
        imageView.setBackgroundDrawable(getResources().getDrawable(R.drawable.selected_image_border));
        imageView.setPadding(3, 3, 3, 3);
    }

    private void getDrawablesList() {

        drawables = new ArrayList<Drawable>();
        drawables.add(getResources().getDrawable(R.drawable.natureimage1));
        drawables.add(getResources().getDrawable(R.drawable.natureimage2));
        drawables.add(getResources().getDrawable(R.drawable.natureimage3));
        drawables.add(getResources().getDrawable(R.drawable.natureimage4));
        drawables.add(getResources().getDrawable(R.drawable.natureimage5));
        drawables.add(getResources().getDrawable(R.drawable.natureimage6));
        drawables.add(getResources().getDrawable(R.drawable.natureimage7));
        drawables.add(getResources().getDrawable(R.drawable.natureimage8));
        drawables.add(getResources().getDrawable(R.drawable.natureimage9));
        drawables.add(getResources().getDrawable(R.drawable.natureimage10));
        drawables.add(getResources().getDrawable(R.drawable.natureimage11));
        drawables.add(getResources().getDrawable(R.drawable.natureimage12));
        drawables.add(getResources().getDrawable(R.drawable.natureimage13));
        drawables.add(getResources().getDrawable(R.drawable.natureimage14));
        drawables.add(getResources().getDrawable(R.drawable.natureimage15));

    }

    private void setSelectedImage(int selectedImagePosition) {

        BitmapDrawable bd = (BitmapDrawable) drawables.get(selectedImagePosition);
        Bitmap b = Bitmap.createScaledBitmap(bd.getBitmap(), (int) (bd.getIntrinsicHeight() * 0.9), (int) (bd.getIntrinsicWidth() * 0.7), false);
        selectedImageView.setImageBitmap(b);
        selectedImageView.setScaleType(ScaleType.FIT_XY);

    }
}

Code for GalleryImageAdapter.java

package com.gallerydemo;

import java.util.List;

import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;

public class GalleryImageAdapter extends BaseAdapter {

    private Activity context;

    private static ImageView imageView;

    private List<Drawable> plotsImages;

    private static ViewHolder holder;

    public GalleryImageAdapter(Activity context, List<Drawable> plotsImages) {

        this.context = context;
        this.plotsImages = plotsImages;

    }

    @Override
    public int getCount() {
        return plotsImages.size();
    }

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {

            holder = new ViewHolder();

            imageView = new ImageView(this.context);

            imageView.setPadding(3, 3, 3, 3);

            convertView = imageView;

            holder.imageView = imageView;

            convertView.setTag(holder);

        } else {

            holder = (ViewHolder) convertView.getTag();
        }

        holder.imageView.setImageDrawable(plotsImages.get(position));

        holder.imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        holder.imageView.setLayoutParams(new Gallery.LayoutParams(150, 90));

        return imageView;
    }

    private static class ViewHolder {
        ImageView imageView;
    }

}

Code for main.xml

<?xmlversion="1.0"encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/selected_imageview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@+id/gallery_relative_layout"
        android:layout_marginLeft="30dip"
        android:layout_marginRight="30dip"
        android:layout_marginTop="30dip" />

    <RelativeLayout
        android:id="@+id/gallery_relative_layout"
        android:layout_width="fill_parent"
        android:layout_height="150dip"
        android:layout_alignParentBottom="true"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/left_arrow_imageview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="15dip"
            android:src="@drawable/arrow_left_disabled" />

        <Gallery
            android:id="@+id/gallery"
            android:layout_width="0dip"
            android:layout_height="150dip"
            android:layout_marginLeft="20dip"
            android:layout_marginRight="20dip"
            android:layout_toLeftOf="@+id/right_arrow_imageview"
            android:layout_toRightOf="@+id/left_arrow_imageview"
            android:spacing="20dip" />

        <ImageView
            android:id="@+id/right_arrow_imageview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="15dip"
            android:src="@drawable/arrow_right_enabled" />
    </RelativeLayout>

</RelativeLayout>

Code for image_border.xml

<?xmlversion="1.0"encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item>
        <shape android:shape="rectangle" >
            <gradient
                android:angle="90"
                android:centerColor="#777777"
                android:endColor="#777777"
                android:startColor="#777777" />
        </shape>
    </item>
    <item
        android:bottom="3dp"
        android:left="3dp"
        android:right="3dp"
        android:top="3dp">
        <shape android:shape="rectangle" >
            <solid android:color="#777777" />
        </shape>
    </item>

</layer-list>

Code for selected_image_border.xml

<?xmlversion="1.0"encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item>
        <shape android:shape="rectangle" >
            <gradient
                android:angle="90"
                android:centerColor="#000"
                android:endColor="#000"
                android:startColor="#000" />
        </shape>
    </item>
    <item
        android:bottom="3dp"
        android:left="3dp"
        android:right="3dp"
        android:top="3dp">
        <shape android:shape="rectangle" >
            <solid android:color="#000" />
        </shape>
    </item>

</layer-list>

Output of this program will be as shown below

galleryDemo

You can download the complete source code for the project from here

8 Comments to "Android Gallery Widget Example and Tutorial"

    *
  • Beso says:

    September 9, 2013 at 7:47 PM -

    How to make the pictures load from url instead of Drawable folder?

  • sandeep says:

    August 21, 2013 at 4:52 PM -

    nice post boss…
    i need little more extension for this. i want show image form /sdcard/Photos/ as a GalleryView

  • CAndres says:

    July 13, 2013 at 2:46 AM -

    A Love You very much! It works very nice, thanks

  • raj says:

    July 4, 2013 at 5:10 PM -

    very nice.

  • Rui Pereira says:

    June 19, 2013 at 9:32 PM -

    Nice post.
    Just a small comment on my part : instead of posting the complete code on the post, just have the relevant parts posted, that way people dont need to go through the entire code to find bits and pieces.

  • John Adkins says:

    May 20, 2013 at 10:57 PM -

    Thank you for posting this. The only thing throwing me is the resources natureimage1 thru natureimage15. They aren’t in any xml file, and I’m hoping for a variable number of images. Am I missing something? Thanks for the help

  • Sumit Gupta says:

    May 14, 2013 at 12:51 PM -

    Very nicely done, thanks for sharing the source code. Very helpful

  • Powerpc says:

    April 2, 2013 at 6:58 PM -

    It crashes in oncreate for android 4.0 http://stackoverflow.com/questions/15746540/loading-resources-oncreate-casusing-java-lang-outofmemoryerror

Leave a Reply

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


five × 1 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Leave a Reply

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


5 − = zero

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Copyright by Mobisoft Infotech LLC 2013, All rights reserved
GET IN TOUCH