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...

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 ...

Working with Android 11 (Changes and Security Features)

 Hello everyone , I am here with new article which is hot topic nowadays "Android 11" .The stable version of Android.  Android 11 is the eleventh major release and 18th version of Android, the mobile operating system developed by the Open Handset Alliance led by Google. It was released on September 8, 2020.It is comes with many security features and other features as well . And it is now compulsory in play store  to upload new apps with API lavel 30 which is compatible with Android 11 and from November onwards old apps also have to update with API 30 .Some other guidelines you can check out from here . Play Store Guidelines So its clear that we have to update our apps with API level 30 .But Android 11 comes with some changes as well which we have to do in our projects. For example from Android developer site "Android 11 (API level 30) further enhances the platform, giving better protection to app and user data on external storage. ". Scoped storage enforcement: Apps...