Table of contents
1.
Introduction
2.
What is Galleryview in Android with example?
3.
Way to Define a Gallery Tag
4.
Important Methods of GalleryView in Android
5.
Functioning of Gallery View
6.
Attributes of Gallery View
7.
Example Application - Step-by-Step Implementation
7.1.
Step 1: Create a New Project in Android Studio
7.2.
Step 2: Working with the XML Files
7.3.
Step 3: Working with the MainActivity File
7.4.
Step 4: Create a New Class CustomizedGalleryAdapter
8.
Frequently Asked Questions
8.1.
Why do we use Gallery view?
8.2.
What are better alternatives for Gallery view?
8.3.
What's the difference between an Android ScrollView and a horizontal ScrollView?
9.
Conclusion
Last Updated: May 8, 2024
Easy

Gallery View in Android

Author Akshit Pant
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In general, a gallery can be best explained as a collection of pictures or images. Have you ever wondered how we can implement a gallery in Android?

In this article, we'll be learning about Gallery View in Android, syntax, functioning, and later, we'll implement it in an application.

Gallery View in Android

But before jumping directly on how Android Studio does this, first having the basic knowledge of Kotlin and how to use it is strongly recommended.

So, let us start understanding how Gallery view works on Android.

What is Galleryview in Android with example?

GalleryView in Android is a deprecated UI widget used to display a collection of images or other views in a horizontal scrolling list. It has been replaced by RecyclerView or ViewPager for better performance and flexibility.

<Gallery
    android:id="@+id/gallery"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

This XML snippet defines a GalleryView in an Android layout file.

Way to Define a Gallery Tag

To define a GalleryView in Android, you can use the <Gallery> tag in your XML layout file. Specify attributes like android:id, android:layout_width, and android:layout_height to customize the appearance and behavior of the GalleryView.

<Gallery
    android:id="@+id/gallery"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

This XML snippet demonstrates the definition of a GalleryView using the <Gallery> tag.

Important Methods of GalleryView in Android

MethodDescription
setAdapter(Adapter adapter)Sets the adapter for the GalleryView to provide data for the items.
setSpacing(int spacing)Sets the spacing between items in the GalleryView.
setCallbackDuringFling(boolean)Sets whether to call getView during a fling.
setUnselectedAlpha(float alpha)Sets the transparency of unselected items in the GalleryView.

These methods are essential for customizing the behavior and appearance of a GalleryView in Android applications.

Functioning of Gallery View

The user will have an 'n' number of items in a horizontal fashion, and the selected item will be located at the center of the horizontal list. The Adapter can be used to add "n" number of items since it serves as a link between the user interface and the data source.

Note: Use of Gallery view now is deprecated.

Attributes of Gallery View

Some of the attributes of Gallery view are given below:

  • id: Used to give Gallery view a distinct identity.
  • padding: Used to give the padding in Gallery view(from all sides: top, bottom, right, left).
  • paddingTop: Used to give the padding on a Gallery's top side.
  • paddingBottom: Used to give the padding on a Gallery's bottom side.
  • paddingLeft: Used to give the padding on a Gallery's left side.
  • paddingRight: Used to give the padding on a Gallery's right side.
  • background: Used to create a Gallery's backdrop(background), and In the background, we have a choice between the colors(from colors.xml) and images(from drawable).
  • animationDuration: Used to specify how long a transition animation should run for.
    Note: Time duration is in milliseconds.
  • unselectedAlpha: Used to make the things that aren't selected have an alpha value(It must be in float value).
  • spacing: Using this In a Gallery, we can adjust the spacing between items(in a horizontal scroll manner).


Let's use these attributes with a working example given below.

Example Application - Step-by-Step Implementation

Step 1: Create a New Project in Android Studio

Open Android Studio, start an empty activity, give a name to your app( Gallery View CN in our case), and let Android do the Gradle syncing.

Step 2: Working with the XML Files

Now, start working on the studio by editing activity_main.xml file as per the user’s need.

Here we will be adding a vertically oriented linear layout in which we will have three components(child): GalleryView, TextView, and ImageView.

Code:

<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/ll_GalleryView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <Gallery
            android:id="@+id/my_galleryView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"/>

        <TextView
            android:id="@+id/myTextView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="40sp"
            android:text="@string/scroll"
            android:textColor="@color/teal_700"
            android:gravity="center"/>

        <ImageView
            android:id="@+id/my_imageView"
            android:layout_marginTop="100dp"
            android:layout_width="match_parent"
            android:layout_gravity="center_horizontal"
            android:layout_height="400dp"
            android:src="@drawable/logo" />

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

Step 3: Working with the MainActivity File

Now, call out the Gallery view in MainActivity.kt using find view, arrange the spacing between items of Gallery view and create on click of images on Gallery view to show them in the Image View of the XML file.

Code:

package com.codingninjas.galleryviewcn

import android.os.Bundle
import android.widget.AdapterView.OnItemClickListener
import android.widget.Gallery
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    lateinit var my_imageView: ImageView
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val my_galleryView = findViewById<Gallery>(R.id.my_galleryView)
        my_imageView = findViewById(R.id.my_imageView)
        my_galleryView.setSpacing(2)
        val myGalleryViewAdapter = GalleryImageAdapter(applicationContext)
        my_galleryView.adapter = myGalleryViewAdapter
        my_galleryView.onItemClickListener =
            OnItemClickListener { parent, v, position, id ->
            // to show the selected image in my_imageView
                my_imageView.setImageResource(myGalleryViewAdapter.n_ImageIds[position])
            }
    }
}

Step 4: Create a New Class CustomizedGalleryAdapter

Now, the last step is to upload the images in the Gallery view using an Adapter. So, for this, make a new file with the location same as that of MainActivity.kt and name it GalleryImageAdapter. 

Code:

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 GalleryImageAdapter extends BaseAdapter {

    private final Context mContext;

    public GalleryImageAdapter(Context context)
    {
        mContext = context;
    }

    public int getCount() {
        return n_ImageIds.length;
    }

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

    public long getItemId(int position) {
        return position;
    }


    // Override method as per user need
    public View getView(int index, View view, ViewGroup viewGroup)
    {
        // TODO Auto-generated method stub
        ImageView iv = new ImageView(mContext);

        iv.setImageResource(n_ImageIds[index]);
        iv.setLayoutParams(new Gallery.LayoutParams(300, 300));
        iv.setScaleType(ImageView.ScaleType.FIT_XY);

        return iv;
    }

    public Integer[] n_ImageIds = {
            R.drawable.logo,
            R.drawable.certificate,
            R.drawable.classroom,
            R.drawable.competition,
            R.drawable.coupans,
            R.drawable.swags,
            R.drawable.ninja,
            R.drawable.test,
            R.drawable.sir,
            R.drawable.face
    };

}

 

Note: R.drawable.logo, R.drawable.certificate,  R.drawable.classroom, R.drawable.competition, R.drawable.coupans, R.drawable.swags, R.drawable.ninja, R.drawable.test, R.drawable.sir, R.drawable.face are the images uploaded to res -> drawable folder. You can choose images as per your requirement(manually or from database).

Output:

     


We can see in the output that at the top of our screen, we have our Gallery view with 10 images(we can use n number of images) which have left and right scroll enabled, and the pic we click on/choose becomes the centre locked image and gets displayed at the bottom of the screen in the Image view.

Frequently Asked Questions

Why do we use Gallery view?

Gallery view is a view that enables us to put widgets in a horizontally scrollable and centre fixed manner.

What are better alternatives for Gallery view?

The use of Gallery class is deprecated in API 16 level, So now we have HorizontalScrollView and ViewPager from support lib, which solves the purpose of Gallery view.

What's the difference between an Android ScrollView and a horizontal ScrollView?

The attributes of ScrollView and HorizontalScrollView are the same. The only difference is that scrollView scrolls the child items vertically, whereas horizontal scroll view scrolls them horizontally.

Conclusion

In this article, we learned about Gallery view and its implementation. We also infer from this article why the Gallery view is necessary and what its alternatives are.
You can head over to our Android Development Course on the Coding Ninjas Website to dive deep into Android Development and build future applications.
We hope this article has helped you enhance your knowledge of the Android UI Gallery view. If you want to learn more, check out our Android UI and Competitive Programming articles. Do upvote this article to help other ninjas grow.
Happy Coding!

Live masterclass