Open In App

GalleryView in Android with Example

Last Updated : 16 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In Android, Gallery is a view that can show items in a center-locked, horizontal scrolling list, and hence the user can able to select a view, and then the user-selected view will be shown in the center of the Horizontal list. “N” number of items can be added by using the Adapter. The adapter is a bridging component between the UI component and the data source. The items given in the adapter will be shown in the gallery in the example. We are going to implement this project using both Java and Kotlin Programming Language for Android.

Important Point: Gallery class was deprecated in API level 16. Instead  other horizontally scrolling widgets are HorizontalScrollView and ViewPager from the support library are available.

Way to Define a Gallery Tag

XML




<!-- By using android:spacing we can give spacing between images
     android:animationDuration="3000" > for animation running -->
<Gallery
  android:id="@+id/languagesGallery"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginTop="100dp"
  android:unselectedAlpha="50"
  android:spacing="5dp"
  android:animationDuration="2000"
  android:padding="10dp" />


 Important Methods of GalleryView in Android

Methods

Description

setAnimationDuration(int)

To set the duration for how long a transition animation should run 

(in milliseconds) whenever there is a change in layout. 

This can be set in xml also via android:animationDuration=”3000″

setSpacing(int)

To set the spacing between items in a Gallery. This can be set in xml 

also via android:spacing=”5dp”

setUnselectedAlpha(float)

To set the alpha on the items that are not selected. This can be set in xml

also via android:unselectedAlpha=”0.25″

Let us see the Implementation of Important Methods: 

Java




// get the reference of Gallery first
Gallery simpleGallery = findViewById(R.id.languagesGallery);
  
// set 3000 milliseconds for animation duration between each items of Gallery
// xml equivalent -> android:animationDuration="2000" 
simpleGallery.setAnimationDuration(2000);
  
// set space between the items of Gallery
// xml equivalent -> android:spacing="15dp"
simpleGallery.setSpacing(15);
  
// set 0.25 value for the alpha of unselected items of Gallery
// xml equivalent -> android:unselectedAlpha="0.25"
simpleGallery.setUnselectedAlpha(0.25f);


Kotlin




// get the reference of Gallery first
val simpleGallery = findViewById<Gallery>(R.id.languagesGallery)
  
// set 3000 milliseconds for animation duration between each items of Gallery
// xml equivalent -> android:animationDuration="2000"
simpleGallery.setAnimationDuration(2000)
  
// set space between the items of Gallery
// xml equivalent -> android:spacing="15dp"
simpleGallery.setSpacing(15)
  
// set 0.25 value for the alpha of unselected items of Gallery
// xml equivalent -> android:unselectedAlpha="0.25"
simpleGallery.setUnselectedAlpha(0.25f)


Attributes of GalleryView

Attributes

Description

id To uniquely identify a Gallery
padding To set the padding from the left, right, and the top or bottom side of a Gallery.
paddingRight To set the padding from the right side of a Gallery.
paddingLeft To set the padding from the left side of a Gallery.
paddingTop To set the padding from the top side of a Gallery.
paddingBottom To set the padding from the bottom side of a Gallery.
padding To set the padding from all the sides of a Gallery.
background

To set the background of a Gallery. For background, either we can

set colors (using colors.xml) or images that are kept under the drawable folder

Via java/kotlin code also, we can set the background color in the below way

simpleGallery.setBackgroundColor(Color.GFGGreencolor); // set the desired color

animationDuration

To set the duration for how long a transition animation should run (in milliseconds)

Via java/kotlin, simpleGallery.setAnimationDuration(<No of milliseconds>); 

spacing

To set the spacing between items in a Gallery. Via java/kotlin, simpleGallery.setSpacing(10); 

// We can set the spacing between items as per our requirement

unselectedAlpha

To set the alpha on the items that are not selected.

Via java/kotlin, simpleGallery.setUnselectedAlpha(0.25f)

Example

A sample GIF is given below to get an idea about what we are going to do in this article. We are going to implement this project using both Java and Kotlin Programming Language for Android.

GalleryView in Android Sample GIF

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.

Step 2: Working with the XML Files

Next, go to the activity_main.xml file, which represents the UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff"
    android:orientation="vertical"
    tools:context=".MainActivity">
  
    <!-- create a ImageView and Gallery -->
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="fill_parent"
        android:layout_height="200dp"
        android:scaleType="fitXY" />
  
    <!-- By using android:spacing we can give spacing between images
         android:animationDuration="3000" -> for animation running -->
    <Gallery
        android:id="@+id/languagesGallery"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:animationDuration="2000"
        android:padding="10dp"
        android:spacing="5dp"
        android:unselectedAlpha="50" />
</LinearLayout>


Step 3: Working with the MainActivity File

Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.

Java




import android.os.Bundle;
import android.widget.Gallery;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
  
public class MainActivity extends AppCompatActivity {
  
    Gallery simpleGallery;
  
    // CustomizedGalleryAdapter is a java/kotlin 
    // class which extends BaseAdapter
    // and implement the override methods.
    CustomizedGalleryAdapter customGalleryAdapter;
    ImageView selectedImageView;
  
    // To show the selected language, we need this
    // array of images, here taken 10 different kind of 
    // most popular programming languages
    int[] images = {
        R.drawable.python,
        R.drawable.javascript,
        R.drawable.java,
        R.drawable.python,
        R.drawable.r,
        R.drawable.python,
        R.drawable.javascript,
        R.drawable.python,
        R.drawable.r,
        R.drawable.javascript
    };
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // Our layout is activity_main
        // get the reference of Gallery. As we are showing 
        // languages it is named as languagesGallery
        // meaningful names will be good for easier understanding
        simpleGallery = (Gallery) findViewById(R.id.languagesGallery);
  
        // get the reference of ImageView
        selectedImageView = (ImageView) findViewById(R.id.imageView);
  
        // initialize the adapter
        customGalleryAdapter = new CustomizedGalleryAdapter(getApplicationContext(), images);
  
        // set the adapter for gallery
        simpleGallery.setAdapter(customGalleryAdapter);
  
        // Let us do item click of gallery and image can be identified by its position
        simpleGallery.setOnItemClickListener((parent, view, position, id) -> {
            // Whichever image is clicked, that is set in the  selectedImageView
            // position will indicate the location of image
            selectedImageView.setImageResource(images[position]);
        });
    }
}


Kotlin




import android.os.Bundle
import android.view.View
import android.widget.Gallery
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
  
class MainActivity : AppCompatActivity() {
  
    private lateinit var simpleGallery: Gallery
  
    // CustomizedGalleryAdapter is a java class which extends BaseAdapter
    // and implement the override methods.
    private lateinit var customGalleryAdapter: CustomizedGalleryAdapter
    private lateinit var selectedImageView: ImageView
  
    // To show the selected language, we need this
    // array of images, here taken 10 different kind of 
    // most popular programming languages
    private var images = intArrayOf(
        R.drawable.python,
        R.drawable.javascript,
        R.drawable.java,
        R.drawable.python,
        R.drawable.r,
        R.drawable.python,
        R.drawable.javascript,
        R.drawable.python,
        R.drawable.r,
        R.drawable.javascript
    )
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // Our layout is activity_main
        // get the reference of Gallery. As we are showing 
        // languages it is named as languagesGallery
        // meaningful names will be good for easier understanding
        simpleGallery = findViewById<View>(R.id.languagesGallery) as Gallery
  
        // get the reference of ImageView
        selectedImageView = findViewById<View>(R.id.imageView) as ImageView
  
        // initialize the adapter
        customGalleryAdapter = CustomizedGalleryAdapter(applicationContext, images)
  
        // set the adapter for gallery
        simpleGallery.adapter = customGalleryAdapter
  
        // Let us do item click of gallery and image can be identified by its position
        simpleGallery.setOnItemClickListener { parent, view, position, id ->
                // Whichever image is clicked, that is set in the  selectedImageView
                // position will indicate the location of image
                selectedImageView.setImageResource(images[position])
            }
    }
}


Step 4: Create a New Class CustomizedGalleryAdapter

This can be in the same location as MainActivity for easier reference. In this step, we create a CustomizedGalleryAdapter and it is extended from BaseAdapter and implements the overridden methods. Inside the code, an ImageView is created at run time in the getView method and finally set the image in the ImageView.

Java




import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
  
public class CustomizedGalleryAdapter extends BaseAdapter {
  
    private final Context context;
    private final int[] images;
  
    public CustomizedGalleryAdapter(Context c, int[] images) {
        context = c;
        this.images = images;
    }
  
    // returns the number of images, in our example it is 10
    public int getCount() {
        return images.length;
    }
  
    // returns the Item  of an item, i.e. for our example we can get the image
    public Object getItem(int position) {
        return position;
    }
  
    // returns the ID of an item
    public long getItemId(int position) {
        return position;
    }
  
    // returns an ImageView view
    public View getView(int position, View convertView, ViewGroup parent) {
        // position argument will indicate the location of image
        // create a ImageView programmatically
        ImageView imageView = new ImageView(context);
  
        // set image in ImageView
        imageView.setImageResource(images[position]);
  
        // set ImageView param
        imageView.setLayoutParams(new Gallery.LayoutParams(200, 200));
        return imageView;
    }
}


Kotlin




import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.Gallery
import android.widget.ImageView
  
class CustomizedGalleryAdapter(private val context: Context, private val images: IntArray) : BaseAdapter() {
      
    // returns the number of images, in our example it is 10
    override fun getCount(): Int {
        return images.size
    }
  
    // returns the Item  of an item, i.e. for our example we can get the image
    override fun getItem(position: Int): Any {
        return position
    }
  
    // returns the ID of an item
    override fun getItemId(position: Int): Long {
        return position.toLong()
    }
  
    // returns an ImageView view
    override fun getView(position: Int, convertView: View, parent: ViewGroup): View {
        // position argument will indicate the location of image
        // create a ImageView programmatically
        val imageView = ImageView(context)
  
        // set image in ImageView
        imageView.setImageResource(images[position])
  
        // set ImageView param
        imageView.layoutParams = Gallery.LayoutParams(200, 200)
        return imageView
    }
}


Output:

On running the android code in android studio, we can able to get the output as shown in the attached video. This is a useful feature that is used across many android apps. We need to consider the important points mentioned earlier. i.e. horizontally scrolling widgets are HorizontalScrollView and ViewPager from the support library are available and hence for the latest devices prefer them.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads