GalleryView in Android with Example - GeeksforGeeks

13 Jul, 2021
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 UI component and data source(It can be an array of items defined in java code or from a database). The items given in the adapter will be shown in the gallery in the example.
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.
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" />
  
Methods
Description
To set the duration for how long a transition animation should run 
(in milliseconds) whenever there is change in layout. 
This can be set in xml also via android:animationDuration=”3000′′
To set the spacing between items in a Gallery. This can be set in xml 
also via android:spacing=”5dp”
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 firstGallery simpleGallery = (Gallery) 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);
Attributes
Description
To set the background of a Gallery. For background, either we can
set colors (using colors.xml) or images which are kept under drawable folder
Via java code also, we can set the background color in the below way
simpleGallery.setBackgroundColor(Color.GFGGreencolor); // set the desired color
To set the duration for how long a transition animation should run (in milliseconds)
Via java, 
simpleGallery.setAnimationDuration(<No of milliseconds>); 
To set the spacing between items in a Gallery. 
Via java,
simpleGallery.setSpacing(10);  // We can set spacing between items as per our requirement
To set the alpha on the items that are not selected.
Via java,
simpleGallery.setUnselectedAlpha(0.25f)
A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Working with the activity_main.xml file
Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file.
XML
<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.java file
 
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
 
Java
import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.Gallery;import android.widget.ImageView;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity {     Gallery simpleGallery;     // CustomizedGalleryAdapter is a java 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(new AdapterView.OnItemClickListener() {            @Override            public void onItemClick(AdapterView<?> parent, View view, int position, long 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.java 
 
This can be in the same location as MainActivity.java 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 Context context;    private 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;    }}
  
 
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.
 
 
singghakshay
android
Android-View
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Retrofit with Kotlin Coroutine in Android
Android Listview in Java with Example
How to Read Data from SQLite Database in Android?
How to Change the Background Color After Clicking the Button in Android?
Flutter - Custom Bottom Navigation Bar
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Initialize an ArrayList in Java