The Wayback Machine - https://web.archive.org/web/20240927085814/https://www.geeksforgeeks.org/galleryview-in-android-with-example/
Open In App

GalleryView in Android with Example

Last Updated : 07 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

idTo uniquely identify a Gallery
paddingTo set the padding from the left, right, and the top or bottom side of a Gallery.
paddingRightTo set the padding from the right side of a Gallery.
paddingLeftTo set the padding from the left side of a Gallery.
paddingTopTo set the padding from the top side of a Gallery.
paddingBottomTo set the padding from the bottom side of a Gallery.
paddingTo 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.

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:android="http://schemas.android.com/apk/res/android"
    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.



Similar Reads

How to Use Fast Android Networking Library in Android with Example?
In Android, we know multiple networking libraries like Retrofit, Volley. We use these libraries specifically for making networking requests like performing actions on API. But Besides that, there is another library called Fast Networking Library which has a few advantages over other libraries. In this tutorial, we will be specifically focusing on l
4 min read
Android Jetpack - WorkManager with Example
WorkManager is an Android Jetpack library that provides a flexible and efficient way to schedule and manage background tasks in your app. It is a powerful and recommended tool for managing background processing in Android applications. With WorkManager, you can schedule asynchronous, deferred, and periodic tasks that need to run even when the app i
5 min read
Android BottomSheet Example in Kotlin
The Bottom Sheet is seen in many of the applications such as Google Drive, Google Maps and most of the applications used the Bottom Sheet to display the data inside the application. In this article, we will take a look at implementing a Bottom Sheet in the Android app using Kotlin in Android Studio. What is Bottom Sheet? Bottom Sheet is a component
5 min read
Spinner in Android with Example
Android Spinner is a view similar to the dropdown list which is used to select one option from the list of options. It provides an easy way to select one item from the list of items and it shows a dropdown list of all values when we click on it. The default value of the android spinner will be the currently selected value and by using Adapter we ca
4 min read
ImageView in Android with Example
ImageView class is used to display any kind of image resource in the android application either it can be android.graphics.Bitmap or android.graphics.drawable.Drawable (it is a general abstraction for anything that can be drawn in Android). ImageView class or android.widget.ImageView inherits the android.view.View class which is the subclass of Kot
4 min read
PhotoView in Android with Example
In this article, PhotoView is added to android. PhotoView aims to help produce an easily usable implementation of a zooming Android ImageView using multi-touch and double-tap. Besides that, it has many more features like it notifying the application when the user taps on the photo or when the displayed matrix gets changed. It provides smooth scroll
2 min read
NestedScrollView in Android with Example
NestedScrollView is just like ScrollView, but it supports acting as both a nested scrolling parent and child on both new and old versions of Android. It is enabled by default. NestedScrollView is used when there is a need for a scrolling view inside another scrolling view. You have seen this in many apps for example when we open a pdf file and when
5 min read
Bundle in Android with Example
It is known that Intents are used in Android to pass to the data from one activity to another. But there is one another way, that can be used to pass the data from one activity to another in a better way and less code space ie by using Bundles in Android. Android Bundles are generally used for passing data from one activity to another. Basically he
6 min read
Activity State Changes In Android with Example
Prerequisites: Activity lifecycle in android As it is known that every Android app has at least one activity associated with it. When the application begins to execute and runs, there are various state changes that activity goes through. Different events some user-triggered and some system triggered can cause an activity to do the transition from o
6 min read
Floating Action Button (FAB) in Android with Example
The floating action button is a bit different button from the ordinary buttons. Floating action buttons are implemented in the app's UI for primary actions (promoted actions) for the users and the actions under the floating action button are prioritized by the developer. For example the actions like adding an item to the existing list. So in this a
8 min read
Theming Floating Action Buttons in Android with Example
Prerequisite: Floating Action Button (FAB) in Android with ExampleExtended Floating Action Button in Android with Example Android application developers want to seek the attention of the users by customizing and theming the android application widgets and keep more traffic of customers only by the design of the application. In this article, it has
12 min read
ArrayAdapter in Android with Example
The Adapter acts as a bridge between the UI Component and the Data Source. It converts data from the data sources into view items that can be displayed into the UI Component. Data Source can be Arrays, HashMap, Database, etc. and UI Components can be ListView, GridView, Spinner, etc. ArrayAdapter is the most commonly used adapter in android. When y
3 min read
SlidingDrawer in Android with Example
SlidingDrawer is a common requirement in android mobiles to view the content whenever needed by sliding horizontally as well as vertically. In this article, let us check out Sliding Drawer which is used to hide the content out from the screen and allows the user to drag a handle to bring the content on the screen whenever needed in a very user-frie
9 min read
MVC (Model View Controller) Architecture Pattern in Android with Example
Developing an android application by applying a software architecture pattern is always preferred by the developers. An architecture pattern gives modularity to the project files and assures that all the codes get covered in Unit testing. It makes the task easy for developers to maintain the software and to expand the features of the application in
8 min read
ViewStub in Android with Example
In Android, ViewStub is a zero-sized invisible View and very flexible in that we can lazily inflate layout resources at runtime. It is a dumb and lightweight view and it has zero dimension. Depending upon the requirement, whenever in need we can inflate at runtime. This is a classic example to handle when there are complicated views to be handled.
6 min read
MVP (Model View Presenter) Architecture Pattern in Android with Example
In the initial stages of Android development, learners do write codes in such a manner that eventually creates a MainActivity class which contains all the implementation logic(real-world business logic) of the application. This approach of app development leads to Android activity gets closely coupled to both UI and the application data processing
12 min read
Include and Merge Tags in Android with Example
Android apps are growing and one important aspect of it is reusability. Sometimes, the complexity of app design will be more and during that time, Android providing very efficient reusable features by means of the <include/> and <merge/> tags. Under <merge/> tags, we can specify a part of the layout that has to come in the main la
4 min read
Theming of Material Design EditText in Android with Example
Prerequisite: Material Design EditText in Android with Examples In the previous article Material Design EditText in Android with Examples Material design Text Fields offers more customization and makes the user experience better than the normal text fields. For example, Icon to clear the entire EditText field, helper text, etc. In this article, it'
4 min read
Theming Material Design Snackbars in Android with Example
In the previous article, it's been discussed Snackbar Material Design Components in Android. In this article, it's been discussed how we can theme material design Snackbar and increase the User Experience. Theming Example 1:This method is done using the styles.xml file. Where we need to override the default style of the Snackbar.Have a look at the
5 min read
RecyclerView using GridLayoutManager in Android With Example
RecyclerView is the improvised version of a ListView in Android. It was first introduced in Marshmallow. Recycler view in Android is the class that extends ViewGroup and implements Scrolling Interface. It can be used either in the form of ListView or in the form of Grid View. How to use RecyclerView as GridView? While implementing Recycler view in
6 min read
Fresco Image Loading Library in Android with Example
Fresco is one of the famous image loading libraries from URLs in Android. It is a powerful library for displaying and managing images from URLs. This library can load images from Users' devices, servers, and other local sources. The most important feature of this library is to show a placeholder image when the image from the URL takes so much time
3 min read
SimpleAdapter in Android with Example
In Android, whenever we want to bind some data which we get from any data source (e.g. ArrayList, HashMap, SQLite, etc.) with a UI component(e.g. ListView, GridView, etc.) then Adapter comes into the picture. Basically Adapter acts as a bridge between the UI component and data sources. Here Simple Adapter is one type of Adapter. It is basically an
7 min read
Interpolator in Android with Example
An interpolator is a function (in the mathematical sense) that outputs values "interpolated" between a range of values that are given to it as input. Interpolation is simply a method to generate new data points between two fixed data points. The exact values of these generated data points are determined by the kind of interpolation is performed. Fo
8 min read
CardView in Android With Example
CardView is a new widget in Android that can be used to display any sort of data by providing a rounded corner layout along with a specific elevation. CardView is the view that can display views on top of each other. The main usage of CardView is that it helps to give a rich feel and look to the UI design. This widget can be easily seen in many dif
3 min read
CardView using RecyclerView in Android with Example
RecyclerView is an extended version of ListView and GridView. It works on the ViewHolder design pattern. With the help of RecyclerView, we can add many extra features to our list of data. Before starting our example on the implementation of CardView in RecyclerView. We should know what CardView and RecyclerView mean. CardView: CardView is an extend
9 min read
Dagger 2 Android Example using Retrofit
Dagger 2 Android implementation is easier and it is based on Dependency Injection Architecture. Dependency Injection is a design pattern, which is a concept of Object-Oriented Programming, where we don’t create an object of another class inside a class using the new keyword (for Java). Instead, we supply the needed object from the outside. It is a
6 min read
Input Events in Android with Example
In Android, there's quite a method to intercept the events from a user's interaction with your application. When considering events within your interface, the approach is to capture the events from the precise View object that the user interacts with. The View class provides the means to try to do so. Within the varied View classes that you're goin
7 min read
TreeView in Android with Example
If you are looking for new UI designs to represent huge data, then there are so many ways to represent this type of data. You can use pie charts, graphs, and many more view types to implement these views. For displaying such huge data then we can prefer using a TreeView. TreeView is similar to that of a tree in which it has a parent node and inside
7 min read
ActionBar in Android with Example
In Android applications, ActionBar is the element present at the top of the activity screen. It is a salient feature of a mobile application that has a consistent presence over all its activities. It provides a visual structure to the app and contains some of the frequently used elements for the users. Android ActionBar was launched by Google in 20
8 min read
ToolBar in Android with Example
In Android applications, Toolbar is a kind of ViewGroup that can be placed in the XML layouts of an activity. It was introduced by the Google Android team during the release of Android Lollipop(API 21). The Toolbar is basically the advanced successor of the ActionBar. It is much more flexible and customizable in terms of appearance and functionalit
9 min read
Article Tags :
Practice Tags :