Programming Tutorials

Gallery sample program in Android

By: Ashley in Android Tutorials on 2011-07-03  

This sample android program shows you how to use Gallery in Android. In this program a listof images is shown as a gallery. When you click on the list, the selected item index is shown on the text view. You can use this ImageAdapter widget and the Gallery object together with the onListItemClick() method to determine the selected index and process accordingly. Remember to copy all your images in your res/drawable folder.

The GalleryDemo.java file is as follows:

package com.javasamples;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;

public class GalleryDemo extends Activity {


	TextView mySelection;
	Gallery myGallery;
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.main);
		mySelection = (TextView) findViewById(R.id.mySelection);		
		
		// Bind the gallery defined in the main.xml
		// Apply a new (customized) ImageAdapter to it.

		myGallery = (Gallery) findViewById(R.id.myGallery);

		myGallery.setAdapter(new ImageAdapter(this));
		
		myGallery.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> parent, View v,
					int position, long id) {
				mySelection.setText(" selected option: " + position );
				
			}

			public void onNothingSelected(AdapterView<?> parent) {
				mySelection.setText("Nothing selected");
				
			}


		});
	}// onCreate

	public class ImageAdapter extends BaseAdapter {
		/** The parent context */
		private Context myContext;
		// Put some images to project-folder: /res/drawable/
		// format: jpg, gif, png, bmp, ...
		private int[] myImageIds = { R.drawable.image1, R.drawable.image2,
				       R.drawable.image3, R.drawable.mbl1 };

		/** Simple Constructor saving the 'parent' context. */
		public ImageAdapter(Context c) {
			this.myContext = c;
		}

		// inherited abstract methods - must be implemented
		// Returns count of images, and individual IDs
		public int getCount() {
			return this.myImageIds.length;
		}

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

		public long getItemId(int position) {
			return position;
		}
		// Returns a new ImageView to be displayed,
		public View getView(int position, View convertView, 
				ViewGroup parent) {

			// Get a View to display image data 					
			ImageView iv = new ImageView(this.myContext);
			iv.setImageResource(this.myImageIds[position]);

			// Image should be scaled somehow
			//iv.setScaleType(ImageView.ScaleType.CENTER);
			//iv.setScaleType(ImageView.ScaleType.CENTER_CROP);			
			//iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
			//iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
			//iv.setScaleType(ImageView.ScaleType.FIT_XY);
			iv.setScaleType(ImageView.ScaleType.FIT_END);
			
			// Set the Width & Height of the individual images
			iv.setLayoutParams(new Gallery.LayoutParams(95, 70));

			return iv;
		}
	}// ImageAdapter
}// AndDemoUI



The output of this program will be as shown in the android emulator below.

The main.xml file in your res/layout folder is as follows:

<?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" 
    > 
<TextView   
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="SDK1.5  /samples/.../view/Gallery1.java" 
    />
    <TextView  
    android:id="@+id/mySelection" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:background="#ff0000ff"
    android:textSize="20px" android:textStyle="bold"/>  
<Gallery 
        android:id="@+id/myGallery" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:gravity="bottom" 
        
/> 
</LinearLayout>






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Android )

Performing Streamed Install adb: failed to install app buildoutputsapkdebugapp-debug.apk: Exception occurred while executing 'install': android.os.ParcelableException: java.io.IOException: Requested internal only, but not enough space

Is it safe to delete userdata-qemu.img userdata-qemu.img.qcow2 files

Get Location of an android phone programmatically

'adb' is not recognized as an internal or external command, operable program or batch file.

Emulator: WARNING | *** No gRPC protection active, consider launching with the -grpc-use-jwt flag.***

Android Preferences - Using Preferences in Android Tutorial

Reading and Writing a file to SD card sample program in Android

Gallery sample program in Android

Progress bar and downloading a file sample program in Android

gradle build failed Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema

adb.exe: no devices/emulators found

Intent in Android to call one activity from another activity.

GridView sample program in Android

Android Send SMS and Make a phone call in Android Application

./gradlew assembleDebug '.' is not recognized as an internal or external command, operable program or batch file.

Latest Articles (in Android)

Keep your android phone awake while debugging

compileSdkVersion vs buildToolsVersion in app/build.gradle

gradle build failed Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema

Gradle, npm, react-native - How are they related?

Emulator: glTexImage2D: got err pre :( 0x506 internal 0x8058 format 0x1908 type 0x1401

Emulator: WARNING | *** No gRPC protection active, consider launching with the -grpc-use-jwt flag.***

./gradlew assembleDebug '.' is not recognized as an internal or external command, operable program or batch file.

'adb' is not recognized as an internal or external command, operable program or batch file.

Performing Streamed Install adb: failed to install app buildoutputsapkdebugapp-debug.apk: Exception occurred while executing 'install': android.os.ParcelableException: java.io.IOException: Requested internal only, but not enough space

Is it safe to delete userdata-qemu.img userdata-qemu.img.qcow2 files

adb.exe: no devices/emulators found

How to start the Android emulator

Get Location of an android phone programmatically

Getting Started with Android

Solution to error: unable to open connection to server due to security error

Related Tutorials

Keep your android phone awake while debugging

compileSdkVersion vs buildToolsVersion in app/build.gradle

gradle build failed Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema

Gradle, npm, react-native - How are they related?

Emulator: glTexImage2D: got err pre :( 0x506 internal 0x8058 format 0x1908 type 0x1401

Emulator: WARNING | *** No gRPC protection active, consider launching with the -grpc-use-jwt flag.***

./gradlew assembleDebug '.' is not recognized as an internal or external command, operable program or batch file.

'adb' is not recognized as an internal or external command, operable program or batch file.

Performing Streamed Install adb: failed to install app buildoutputsapkdebugapp-debug.apk: Exception occurred while executing 'install': android.os.ParcelableException: java.io.IOException: Requested internal only, but not enough space

Is it safe to delete userdata-qemu.img userdata-qemu.img.qcow2 files

adb.exe: no devices/emulators found

How to start the Android emulator

Get Location of an android phone programmatically

Getting Started with Android

Solution to error: unable to open connection to server due to security error