Android Implementing ViewPager Into GridView Tutorial
Last Updated: June 7, 2013
In this tutorial, you will learn how to implement a ViewPager into GridView in your Android application. A GridView allows you to show images in a grid form and ViewPager allows the user to flip left and right through images. We will create a GridView and on image click will show a ViewPager that will allow the user to flip left and right through the images. So lets begin…
Create a new project in Eclipse File > New > Android Application Project. Fill in the details and name your project ViewPagerGridView.
Application Name : ViewPagerGridView
Project Name : ViewPagerGridView
Package Name : com.androidbegin.viewpagergridview
Open your MainActivity.java and paste the following code.
MainActivity.java
package com.androidbegin.viewpagergridview; import android.os.Bundle; import android.app.Activity; import android.content.Intent; import android.view.Menu; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.Toast; import android.view.View; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set title for the GridView setTitle("GridView"); // Get the view from grid_view.xml setContentView(R.layout.grid_view); // Set the images from ImageAdapter.java to GridView GridView gridview = (GridView) findViewById(R.id.gridview); gridview.setAdapter(new ImageAdapter(this)); // Listening to GridView item click gridview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { // Launch ImageViewPager.java on selecting GridView Item Intent i = new Intent(getApplicationContext(), ImageViewPager.class); // Show a simple toast message for the item position Toast.makeText(MainActivity.this, "" + position, Toast.LENGTH_SHORT).show(); // Send the click position to ImageViewPager.java using intent i.putExtra("id", position); // Start ImageViewPager startActivity(i); } }); } // Not using options menu for this tutorial @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
This activity retrieves images from an image adapter and sets into the gridview and on gridview item click will capture the selected position and image and pass to a new activity. A toast message will show the current item clicked position.
Next, create an XML graphical layout for your MainActivity. Go to res > layout > Right Click on layout > New > Android XML File
Name your new XML file grid_view.xml and paste the following code.
grid_view.xml
<?xml version="1.0" encoding="utf-8"?> <GridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/gridview" android:layout_width="fill_parent" android:layout_height="fill_parent" android:columnWidth="90dp" android:numColumns="auto_fit" android:verticalSpacing="10dp" android:horizontalSpacing="10dp" android:stretchMode="columnWidth" android:gravity="center" />
We have prepared some sample images for this tutorial. Insert your downloaded sample images into your res > drawable-hdpi.
Sample Images
[wpfilebase tag=file id=25 tpl=download-button /]
Next, create an image adapter class. Go to File > New > Class and name it ImageAdapter.java. Select your package named com.androidbegin.viewpagergridview and click Finish.
Open your ImageAdapter.java and paste the following code.
ImageAdapter.java
package com.androidbegin.viewpagergridview; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; public class ImageAdapter extends BaseAdapter { private Context mContext; public ImageAdapter(Context c) { mContext = c; } public int getCount() { return mThumbIds.length; } public Object getItem(int position) { return mThumbIds[position]; } public long getItemId(int position) { return 0; } // Create a new ImageView for each item referenced by the Adapter public View getView(int position, View convertView, ViewGroup parent) { ImageView imageView; if (convertView == null) { // If it's not recycled, initialize some attributes imageView = new ImageView(mContext); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); } else { imageView = (ImageView) convertView; } imageView.setImageResource(mThumbIds[position]); return imageView; } // References to our images in res > drawable public Integer[] mThumbIds = { R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_4, R.drawable.sample_5, R.drawable.sample_6, R.drawable.sample_7, R.drawable.sample_8, R.drawable.sample_9, R.drawable.sample_10, R.drawable.sample_11, R.drawable.sample_12, R.drawable.sample_13, R.drawable.sample_14, R.drawable.sample_15, R.drawable.sample_16, R.drawable.sample_17, R.drawable.sample_18 }; }
This image adapter class retrieves the images from the drawable folder and sets it into the imageviews.
Next, create an image view pager class. Go to File > New > Class and name it ImageViewPager.java. Select your package named com.androidbegin.viewpagergridview and click Finish.
Open your ImageViewPager.java and paste the following code.
ImageViewPager.java
package com.androidbegin.viewpagergridview; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.widget.ImageView; public class ImageViewPager extends Activity { // Declare Variable int position; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set title for the ViewPager setTitle("ViewPager"); // Get the view from view_pager.xml setContentView(R.layout.view_pager); // Retrieve data from MainActivity on item click event Intent p = getIntent(); position = p.getExtras().getInt("id"); ImageAdapter imageAdapter = new ImageAdapter(this); List<ImageView> images = new ArrayList<ImageView>(); // Retrieve all the images for (int i = 0; i < imageAdapter.getCount(); i++) { ImageView imageView = new ImageView(this); imageView.setImageResource(imageAdapter.mThumbIds[i]); imageView.setScaleType(ImageView.ScaleType.CENTER); images.add(imageView); } // Set the images into ViewPager ImagePagerAdapter pageradapter = new ImagePagerAdapter(images); ViewPager viewpager = (ViewPager) findViewById(R.id.pager); viewpager.setAdapter(pageradapter); // Show images following the position viewpager.setCurrentItem(position); } }
This class retrieves all the images from image adapter using intent and pass the current selected image into an imageview.
Next, create an image view pager class. Go to File > New > Class and name it ImagePagerAdapter.java. Select your package named com.androidbegin.viewpagergridview and click Finish.
Open your ImagePagerAdapter.java and paste the following code.
ImagePagerAdapter.java
package com.androidbegin.viewpagergridview; import java.util.List; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; public class ImagePagerAdapter extends PagerAdapter { private List<ImageView> images; public ImagePagerAdapter(List<ImageView> images) { this.images = images; } @Override public Object instantiateItem(ViewGroup container, int position) { ImageView imageView = images.get(position); container.addView(imageView); return imageView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView(images.get(position)); } @Override public int getCount() { return images.size(); } @Override public boolean isViewFromObject(View view, Object o) { return view == o; } }
This class helps to remove and insert images into the imageview while flipping the viewpager left or right.
Next, create an XML graphical layout for your viewpager. Go to res > layout > Right Click on layout > New > Android XML File
Name your new XML file view_pager.xml and paste the following code.
view_pager.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout 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.support.v4.view.ViewPager android:id="@+id/pager" android:layout_width="wrap_content" android:layout_height="wrap_content" > </android.support.v4.view.ViewPager> </RelativeLayout>
Next, change the application name and texts. Open your strings.xml in your res > values folder and paste the following code.
strings.xml
<resources> <string name="app_name">ViewPager GridView</string> <string name="hello_world">Hello world!</string> <string name="menu_settings">Settings</string> <string name="title_activity_main">ViewPager GridView</string> </resources>
In your AndroidManifest.xml, we need to declare an activity. Open your AndroidManifest.xml and paste the following code.
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androidbegin.viewpagergridview" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/title_activity_main" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".ImageViewPager" > </activity> </application> </manifest>
Output:
Source Code
[purchase_link id=”7957″ text=”Purchase to Download Source Code” style=”button” color=”green”]
this is awesome tutorial.. it solved my problem .. thank u :)
Jiya Chaudhary
Android Implementing ViewPager Into GridView Tutorial
HiI just ask something to u to when i performing Operation on ImageView Reside on ViewPager like Roate, and scale .... That time the effects will only display on First and last item of ViewPager Item. i don't know why this is happening.can u please give solution for this problem.thanks
Gaurav Mandlik
Android Implementing ViewPager Into GridView Tutorial
androidbegin, i want to add zoom in/zoom out function in this tamplet. plz anyone help me
Shafqat Mehmood
Android Implementing ViewPager Into GridView Tutorial
dear, i want to add zoom in/zoom out function in this tamplet. plz anyone help me
Shafqat Mehmood
Android Implementing ViewPager Into GridView Tutorial