Skip to main content

How to Create Image Gallery by View Pager In Android

 In some application we have requirement of Image Gallery in which all respective images will show on single UI like Image Gallery App. In this blog we will learn about how to create Image gallery app using View Pager.

before going further here is brief about View Pager:

Layout manager that allows the user to flip left and right through pages of data. You supply an implementation of a PagerAdapter to generate the pages that the view shows. ViewPager is most often used in conjunction with android. app.

So let's start making our App Step by Step.


Step 1: Create activity_main.xml and before this make 2 icons prev and next under mipmap folder.

 <?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:orientation="vertical"  
   tools:context=".MainActivity">  
   <LinearLayout  
     android:layout_width="match_parent"  
     android:layout_height="0dp"  
     android:layout_weight="0.8"  
     android:orientation="horizontal">  
     <ImageView  
       android:id="@+id/prev"  
       android:layout_width="0dp"  
       android:layout_height="wrap_content"  
       android:layout_gravity="center"  
       android:layout_weight="0.1"  
       android:src="@mipmap/prev" />  
     <android.support.v4.view.ViewPager  
       android:id="@+id/view_pager"  
       android:layout_width="0dp"  
       android:layout_height="wrap_content"  
       android:layout_weight="0.8">  
     </android.support.v4.view.ViewPager>  
     <ImageView  
       android:id="@+id/next"  
       android:layout_width="0dp"  
       android:layout_height="wrap_content"  
       android:layout_gravity="center"  
       android:layout_weight="0.1"  
       android:src="@mipmap/next" />  
   </LinearLayout>  
   <HorizontalScrollView  
     android:layout_width="match_parent"  
     android:layout_height="0dp"  
     android:layout_weight="0.2">  
     <LinearLayout  
       android:id="@+id/container"  
       android:layout_width="wrap_content"  
       android:layout_height="wrap_content"  
       android:orientation="horizontal" />  
   </HorizontalScrollView>  
 </LinearLayout>  

Step 2: Its time to add some more images which we want to show in mipmap folder. we have added a.png,b.png,c.png,d.png,e.png,f.png and g.png icons . 

Step 3: Create fragment_page.xml inside layout folder

 <FrameLayout 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="com.droidmedium">  
   <ImageView  
     android:id="@+id/image"  
     android:layout_width="match_parent"  
     android:contentDescription="@string/app_name"  
     android:layout_height="match_parent" />  
 </FrameLayout>  

Step 4 : Now create item_image.xml inside layout folder

 <?xml version="1.0" encoding="utf-8"?>  
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:orientation="horizontal">  
   <ImageView  
     android:id="@+id/img_thumb"  
     android:layout_width="80dp"  
     android:layout_height="80dp"  
     android:layout_marginTop="5dp"  
     android:scaleType="centerCrop" />  
 </LinearLayout>  

Step 5: Create PageFragment.java file 

 package com.droidmedium;  
 import android.graphics.Bitmap;  
 import android.graphics.BitmapFactory;  
 import android.os.Bundle;  
 import android.support.v4.app.Fragment;  
 import android.view.LayoutInflater;  
 import android.view.View;  
 import android.view.ViewGroup;  
 import android.widget.ImageView;  
 public class PageFragment extends Fragment {  
   private int imageResource;  
   private Bitmap bitmap;  
   public static PageFragment getInstance(int resourceID) {  
     PageFragment f = new PageFragment();  
     Bundle args = new Bundle();  
     args.putInt("image_source", resourceID);  
     f.setArguments(args);  
     return f;  
   }  
   @Override  
   public void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     imageResource = getArguments().getInt("image_source");  
   }  
   @Override  
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
     return inflater.inflate(R.layout.fragment_page, container, false);  
   }  
   @Override  
   public void onViewCreated(View view, Bundle savedInstanceState) {  
     super.onViewCreated(view, savedInstanceState);  
     ImageView imageView = (ImageView) view.findViewById(R.id.image);  
     BitmapFactory.Options o = new BitmapFactory.Options();  
     o.inSampleSize = 4;  
     o.inDither = false;  
     bitmap = BitmapFactory.decodeResource(getResources(), imageResource, o);  
     imageView.setImageBitmap(bitmap);  
   }  
   @Override  
   public void onDestroy() {  
     super.onDestroy();  
     bitmap.recycle();  
     bitmap = null;  
   }  
 }  

Step 6: Create ViewPagerAdapter.java file

 package com.droidmedium;  
 import android.support.v4.app.Fragment;  
 import android.support.v4.app.FragmentManager;  
 import android.support.v4.app.FragmentStatePagerAdapter;  
 import java.util.List;  
 public class ViewPagerAdapter extends FragmentStatePagerAdapter {  
   private List<Integer> images;  
   public ViewPagerAdapter(FragmentManager fm, List<Integer> imagesList) {  
     super(fm);  
     this.images = imagesList;  
   }  
   @Override  
   public Fragment getItem(int position) {  
     return PageFragment.getInstance(images.get(position));  
   }  
   @Override  
   public int getCount() {  
     return images.size();  
   }  
 }  

Step 7 : Now finally our MainActivity.java

 package com.droidmedium;  
 import android.graphics.Bitmap;  
 import android.graphics.BitmapFactory;  
 import android.os.Bundle;  
 import android.support.v4.app.FragmentStatePagerAdapter;  
 import android.support.v4.view.ViewPager;  
 import android.support.v7.app.AppCompatActivity;  
 import android.view.View;  
 import android.widget.ImageView;  
 import android.widget.LinearLayout;  
 import java.util.ArrayList;  
 public class MainActivity extends AppCompatActivity {  
   private ArrayList<Integer> images;  
   private BitmapFactory.Options options;  
   private ViewPager viewPager;  
   private View btnNext, btnPrev;  
   private FragmentStatePagerAdapter adapter;  
   private LinearLayout thumbnailsContainer;  
   private final static int[] resourceIDs = new int[]{R.mipmap.a, R.mipmap.b,  
       R.mipmap.c, R.mipmap.d, R.mipmap.e, R.mipmap.f, R.mipmap.g};  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     images = new ArrayList<>();  
     //find view by id  
     viewPager = (ViewPager) findViewById(R.id.view_pager);  
     thumbnailsContainer = (LinearLayout) findViewById(R.id.container);  
     btnNext = findViewById(R.id.next);  
     btnPrev = findViewById(R.id.prev);  
     btnPrev.setOnClickListener(onClickListener(0));  
     btnNext.setOnClickListener(onClickListener(1));  
     setImagesData();  
     // init viewpager adapter and attach  
     adapter = new ViewPagerAdapter(getSupportFragmentManager(), images);  
     viewPager.setAdapter(adapter);  
     inflateThumbnails();  
   }  
   private View.OnClickListener onClickListener(final int i) {  
     return new View.OnClickListener() {  
       @Override  
       public void onClick(View v) {  
         if (i > 0) {  
           //next page  
           if (viewPager.getCurrentItem() < viewPager.getAdapter().getCount() - 1) {  
             viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);  
           }  
         } else {  
           //previous page  
           if (viewPager.getCurrentItem() > 0) {  
             viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);  
           }  
         }  
       }  
     };  
   }  
   private void setImagesData() {  
     for (int i = 0; i < resourceIDs.length; i++) {  
       images.add(resourceIDs[i]);  
     }  
   }  
   private void inflateThumbnails() {  
     for (int i = 0; i < images.size(); i++) {  
       View imageLayout = getLayoutInflater().inflate(R.layout.item_image, null);  
       ImageView imageView = (ImageView) imageLayout.findViewById(R.id.img_thumb);  
       imageView.setOnClickListener(onChagePageClickListener(i));  
       options = new BitmapFactory.Options();  
       options.inSampleSize = 3;  
       options.inDither = false;  
       Bitmap bitmap = BitmapFactory.decodeResource(getResources(), images.get(i), options );  
       imageView.setImageBitmap(bitmap);  
       //set to image view  
       imageView.setImageBitmap(bitmap);  
       //add imageview  
       thumbnailsContainer.addView(imageLayout);  
     }  
   }  
   private View.OnClickListener onChagePageClickListener(final int i) {  
     return new View.OnClickListener() {  
       @Override  
       public void onClick(View v) {  
         viewPager.setCurrentItem(i);  
       }  
     };  
   }  
 }  

our final application will look like this:




That's All .Thank you .


Comments

Popular posts from this blog

How to Download Apk file from Url and Install Programmatically

In this post we learn about download apk file from server or website and then install it Programmatically in Phone. Sometimes we have to download external apk file from server and then install if downloading successfully finished.For this we use AsyncTask class  for background process. So here is Code Snippet for this task.Lets Start :- Before this we have to add these Permissions in Manifest.xml file : <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> DownloadNewVersion.java class DownloadNewVersion extends AsyncTask<String,Integer,Boolean> { @Override protected void onPreExecute() { super.onPreExecute(); bar = new ProgressDialog(getActivity()); bar.setCancelable(false); bar.setMessage("Downl...

Solution of Image not Loaded or Auto Suggestions not working in Android Studio

Sometimes we face issue when some images are not loaded or showing in Android Studio . It shows that image not loaded try to open it externally to fix format problem .It cause when some gradle files are corrupted. also if you try auto suggestions not working in xml layout files like  you can try Invalidate Caches and Restart in Android Studio's File Menu option but you will get no result . So here are some steps to follow to remove this type of problem: Step 1: Close your Android Studio Completely. Go to your User Folder - on Windows 7/8 this would be: [SYSDRIVE]:\Users[your username] (ex. C:\Users\DroidMedium\) there you find a folder with name .AndroidStudio3.5  *( i am using Android Studio 3.5.1 version your version may be different according to your Android Studio version) open this folder now you will find two folders Go to System folder  C:\Users\DroidMedium\.AndroidStudio3.5\System\ Step 2: Now under System Folder you will find Caches folder Delete the Folder Com...

How to Implement Item Click Interface in Android?

In Android development, creating interactive lists is essential to most apps. Often, these lists include items that users can click on to trigger actions such as opening a new screen or displaying more information. In this tutorial, we’ll walk through how to implement an item click interface in Android using Java and XML. By the end of this guide, you’ll know how to create a RecyclerView with an item click listener that responds to user taps. This approach is widely used in modern Android development because RecyclerView is both flexible and efficient. Step 1: Set Up Your Android Project First, create a new Android project in Android Studio. Make sure to choose Java as the programming language. Step 2: Add Dependencies Make sure that you have the required dependencies for RecyclerView in your build.gradle file. If not, add them like this: dependencies {     implementation 'androidx.recyclerview:recyclerview:1.2.1' } Sync the project after adding the dependency. Step 3: Define ...