SlideShare a Scribd company logo
1 of 13
GridView
Tutorial
Perfect APK
Android GridView Tutorial
GridViews provide an appealing way of displaying a collection of items. In cases in which the order of the items is not
important, and when items can be displayed as icons or thumbnails, a GridView is often a good choice. In other
cases you might want to consider other types of views, such as a ListView.
In this tutorial you learn how to properly use a GridView in your Android apps, by following a GridView example for
understanding the building blocks, patterns, and best practices. Please note that the icon set for this example was
created by Design Deck.
Building Blocks
Every GridView requires the following elements, although some of the them may be hidden by using default
components provided in the Android SDK:
● Item Layout File - a GridView item XML layout file to be used by the adapter. In this tutorial we will be using
a layout that contains an ImageView for the icon, and aTextView for the title.
● Parent View Layout File - the layout file for the activity or fragment. In this tutorial we will be using a
RelativeLayout that contains a single GridView.
● Data Container - used for holding the data of a single GridView item. May be as simple as a String or a
complex class. In this tutorial we will be using a class that includes an icon and a title.
● Adapter - used for creating the views of the GridView items. In this tutorial we will be using a custom
adapter that extends the BaseAdapter class.
● Activity or Fragment - the Activity or Fragment in which the GridView is displayed.
Item Layout File
The item layout file is used by the adapter for creating the item view. Below is an example of a GridView item:
The item view is described in the res/layout/gridview_item.xml file below:
1. <?xml version="1.0" encoding="utf-8"?>
2. <!-- the parent view -->
3. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
4. android:layout_width="match_parent"
5. android:layout_height="match_parent"
6. android:layout_gravity="center"
7. android:gravity="center"
Item Layout File
<!-- the ImageView for the icon -->
1. <ImageView android:id="@+id/ivIcon"
2. android:layout_width="wrap_content"
3. android:layout_height="wrap_content"
4. android:padding="1dp"
5. android:contentDescription="@string/icon_content_description"
6. android:scaleType="fitXY"
7. android:layout_alignParentTop="true"
8. android:layout_centerHorizontal="true" />
9.
10. <!-- the TextView for the title -->
11. <TextView android:id="@+id/tvTitle"
12. android:layout_below="@id/ivIcon"
13. android:layout_width="wrap_content"
14. android:layout_height="wrap_content"
15. android:lines="1"
16. android:gravity="center_horizontal"
17. android:layout_centerHorizontal="true"
18. android:textAppearance="@android:style/TextAppearance.Medium" />
19. </RelativeLayout>
Parent View Layout File
In this tutorial the GridView is displayed inside a fragment. The fragment view is described in the res/layout/fragment_gridview.xml file below:
1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:tools="http://schemas.android.com/tools"
3. android:layout_width="match_parent"
4. android:layout_height="match_parent"
5. tools:context=".GridViewFragment" >
6.
7. <GridView android:id="@+id/gridView"
8. android:layout_width="fill_parent"
9. android:layout_height="fill_parent"
10. android:columnWidth="80dp"
Data Container
The GridViewItem class below is used for holding the data of the GridView item:
1. public class GridViewItem {
2. public final Drawable icon; // the drawable for the ListView item ImageView
3. public final String title; // the text for the GridView item title
4.
5. public ListViewItem(Drawable icon, String title) {
6. this.icon = icon;
7. this.title = title;
8. }
9. }
Adapter
The adapter class in this example extends the BaseAdapter abstract class. The getView() method is used by the adapter for creating the
item view using the item layout file. It uses the View Holder pattern which prevents using findViewById() repeatedly. Below is the
GridViewAdapter class used in this example:
1. public class GridViewAdapter extends BaseAdapter {
2. private Context mContext;
3. private List<GridViewItem> mItems;
4.
5. public GridViewAdapter(Context context, List<GridViewItem> items) {
6. mContext = context;
7. mItems = items;
8. }
9.
10. @Override
11. public int getCount() {
Adapter
1. @Override
2. public View getView(int position, View convertView, ViewGroup parent) {
3. ViewHolder viewHolder;
4.
5. if(convertView == null) {
6. // inflate the GridView item layout
7. LayoutInflater inflater = LayoutInflater.from(mContext);
8. convertView = inflater.inflate(R.layout.gridview_item, parent, false);
9.
10. // initialize the view holder
11. viewHolder = new ViewHolder();
12. viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon);
13. viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
14. convertView.setTag(viewHolder);
15. } else {
16. // recycle the already inflated view
17. viewHolder = (ViewHolder) convertView.getTag();
18. }
19.
20. // update the item view
21. GridViewItem item = mItems.get(position);
22. viewHolder.ivIcon.setImageDrawable(item.icon);
23. viewHolder.tvTitle.setText(item.title);
24.
25. return convertView;
26. }
Adapter
1. /**
2. * The view holder design pattern prevents using findViewById()
3. * repeatedly in the getView() method of the adapter.
4. *
5. * @see http://developer.android.com/training/improving-layouts/smooth-
scrolling.html#ViewHolder
6. */
7. private static class ViewHolder {
8. ImageView ivIcon;
9. TextView tvTitle;
10. }
11. }
Activity of Fragment
In this example a Fragment is used for displaying the GridView. The GridViewDemoFragment class below extends the Fragment class and
implements the OnItemClickListener interface for handling GridView item clicks in the onItemClick() method:
1. public class GridViewDemoFragment extends Fragment implements OnItemClickListener {
2. private List<GridViewItem> mItems; // GridView items list
3. private GridViewAdapter mAdapter; // GridView adapter
4.
5. @Override
6. public void onAttach(Activity activity) {
7. super.onAttach(activity);
8.
9. // set the title for the action bar
10. final ActionBar actionBar = activity.getActionBar();
Activity of Fragment
1. @Override
2. public void onCreate(Bundle savedInstanceState) {
3. super.onCreate(savedInstanceState);
4.
5. // initialize the items list
6. mItems = new ArrayList<GridViewItem>();
7. Resources resources = getResources();
8.
9. mItems.add(new GridViewItem(resources.getDrawable(R.drawable.aim),
getString(R.string.aim)));
10. :
11. mItems.add(new GridViewItem(resources.getDrawable(R.drawable.youtube),
getString(R.string.youtube)));
12. }
Activity of Fragment
1. @Override
2. public View onCreateView(LayoutInflater inflater, ViewGroup container,
3. Bundle savedInstanceState) {
4. // inflate the root view of the fragment
5. View fragmentView = inflater.inflate(R.layout.fragment_gridview, container, false);
6.
7. // initialize the adapter
8. mAdapter = new GridViewAdapter(getActivity(), mItems);
9.
10. // initialize the GridView
11. GridView gridView = (GridView) fragmentView.findViewById(R.id.gridView);
12. gridView.setAdapter(mAdapter);
13. gridView.setOnItemClickListener(this);
14.
15. return fragmentView;
16. }
17.
18. @Override
19. public void onItemClick(AdapterView<?> parent, View view, int position,
20. long id) {
21. // retrieve the GridView item
22. GridViewItem item = mItems.get(position);
23.
24. // do something
25. Toast.makeText(getActivity(), item.title, Toast.LENGTH_SHORT).show();
26. }
27. }

More Related Content

Recently uploaded

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 

Recently uploaded (20)

Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 

Featured

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Android GridView Tutorial

  • 2. Android GridView Tutorial GridViews provide an appealing way of displaying a collection of items. In cases in which the order of the items is not important, and when items can be displayed as icons or thumbnails, a GridView is often a good choice. In other cases you might want to consider other types of views, such as a ListView. In this tutorial you learn how to properly use a GridView in your Android apps, by following a GridView example for understanding the building blocks, patterns, and best practices. Please note that the icon set for this example was created by Design Deck.
  • 3. Building Blocks Every GridView requires the following elements, although some of the them may be hidden by using default components provided in the Android SDK: ● Item Layout File - a GridView item XML layout file to be used by the adapter. In this tutorial we will be using a layout that contains an ImageView for the icon, and aTextView for the title. ● Parent View Layout File - the layout file for the activity or fragment. In this tutorial we will be using a RelativeLayout that contains a single GridView. ● Data Container - used for holding the data of a single GridView item. May be as simple as a String or a complex class. In this tutorial we will be using a class that includes an icon and a title. ● Adapter - used for creating the views of the GridView items. In this tutorial we will be using a custom adapter that extends the BaseAdapter class. ● Activity or Fragment - the Activity or Fragment in which the GridView is displayed.
  • 4. Item Layout File The item layout file is used by the adapter for creating the item view. Below is an example of a GridView item: The item view is described in the res/layout/gridview_item.xml file below: 1. <?xml version="1.0" encoding="utf-8"?> 2. <!-- the parent view --> 3. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 4. android:layout_width="match_parent" 5. android:layout_height="match_parent" 6. android:layout_gravity="center" 7. android:gravity="center"
  • 5. Item Layout File <!-- the ImageView for the icon --> 1. <ImageView android:id="@+id/ivIcon" 2. android:layout_width="wrap_content" 3. android:layout_height="wrap_content" 4. android:padding="1dp" 5. android:contentDescription="@string/icon_content_description" 6. android:scaleType="fitXY" 7. android:layout_alignParentTop="true" 8. android:layout_centerHorizontal="true" /> 9. 10. <!-- the TextView for the title --> 11. <TextView android:id="@+id/tvTitle" 12. android:layout_below="@id/ivIcon" 13. android:layout_width="wrap_content" 14. android:layout_height="wrap_content" 15. android:lines="1" 16. android:gravity="center_horizontal" 17. android:layout_centerHorizontal="true" 18. android:textAppearance="@android:style/TextAppearance.Medium" /> 19. </RelativeLayout>
  • 6. Parent View Layout File In this tutorial the GridView is displayed inside a fragment. The fragment view is described in the res/layout/fragment_gridview.xml file below: 1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2. xmlns:tools="http://schemas.android.com/tools" 3. android:layout_width="match_parent" 4. android:layout_height="match_parent" 5. tools:context=".GridViewFragment" > 6. 7. <GridView android:id="@+id/gridView" 8. android:layout_width="fill_parent" 9. android:layout_height="fill_parent" 10. android:columnWidth="80dp"
  • 7. Data Container The GridViewItem class below is used for holding the data of the GridView item: 1. public class GridViewItem { 2. public final Drawable icon; // the drawable for the ListView item ImageView 3. public final String title; // the text for the GridView item title 4. 5. public ListViewItem(Drawable icon, String title) { 6. this.icon = icon; 7. this.title = title; 8. } 9. }
  • 8. Adapter The adapter class in this example extends the BaseAdapter abstract class. The getView() method is used by the adapter for creating the item view using the item layout file. It uses the View Holder pattern which prevents using findViewById() repeatedly. Below is the GridViewAdapter class used in this example: 1. public class GridViewAdapter extends BaseAdapter { 2. private Context mContext; 3. private List<GridViewItem> mItems; 4. 5. public GridViewAdapter(Context context, List<GridViewItem> items) { 6. mContext = context; 7. mItems = items; 8. } 9. 10. @Override 11. public int getCount() {
  • 9. Adapter 1. @Override 2. public View getView(int position, View convertView, ViewGroup parent) { 3. ViewHolder viewHolder; 4. 5. if(convertView == null) { 6. // inflate the GridView item layout 7. LayoutInflater inflater = LayoutInflater.from(mContext); 8. convertView = inflater.inflate(R.layout.gridview_item, parent, false); 9. 10. // initialize the view holder 11. viewHolder = new ViewHolder(); 12. viewHolder.ivIcon = (ImageView) convertView.findViewById(R.id.ivIcon); 13. viewHolder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle); 14. convertView.setTag(viewHolder); 15. } else { 16. // recycle the already inflated view 17. viewHolder = (ViewHolder) convertView.getTag(); 18. } 19. 20. // update the item view 21. GridViewItem item = mItems.get(position); 22. viewHolder.ivIcon.setImageDrawable(item.icon); 23. viewHolder.tvTitle.setText(item.title); 24. 25. return convertView; 26. }
  • 10. Adapter 1. /** 2. * The view holder design pattern prevents using findViewById() 3. * repeatedly in the getView() method of the adapter. 4. * 5. * @see http://developer.android.com/training/improving-layouts/smooth- scrolling.html#ViewHolder 6. */ 7. private static class ViewHolder { 8. ImageView ivIcon; 9. TextView tvTitle; 10. } 11. }
  • 11. Activity of Fragment In this example a Fragment is used for displaying the GridView. The GridViewDemoFragment class below extends the Fragment class and implements the OnItemClickListener interface for handling GridView item clicks in the onItemClick() method: 1. public class GridViewDemoFragment extends Fragment implements OnItemClickListener { 2. private List<GridViewItem> mItems; // GridView items list 3. private GridViewAdapter mAdapter; // GridView adapter 4. 5. @Override 6. public void onAttach(Activity activity) { 7. super.onAttach(activity); 8. 9. // set the title for the action bar 10. final ActionBar actionBar = activity.getActionBar();
  • 12. Activity of Fragment 1. @Override 2. public void onCreate(Bundle savedInstanceState) { 3. super.onCreate(savedInstanceState); 4. 5. // initialize the items list 6. mItems = new ArrayList<GridViewItem>(); 7. Resources resources = getResources(); 8. 9. mItems.add(new GridViewItem(resources.getDrawable(R.drawable.aim), getString(R.string.aim))); 10. : 11. mItems.add(new GridViewItem(resources.getDrawable(R.drawable.youtube), getString(R.string.youtube))); 12. }
  • 13. Activity of Fragment 1. @Override 2. public View onCreateView(LayoutInflater inflater, ViewGroup container, 3. Bundle savedInstanceState) { 4. // inflate the root view of the fragment 5. View fragmentView = inflater.inflate(R.layout.fragment_gridview, container, false); 6. 7. // initialize the adapter 8. mAdapter = new GridViewAdapter(getActivity(), mItems); 9. 10. // initialize the GridView 11. GridView gridView = (GridView) fragmentView.findViewById(R.id.gridView); 12. gridView.setAdapter(mAdapter); 13. gridView.setOnItemClickListener(this); 14. 15. return fragmentView; 16. } 17. 18. @Override 19. public void onItemClick(AdapterView<?> parent, View view, int position, 20. long id) { 21. // retrieve the GridView item 22. GridViewItem item = mItems.get(position); 23. 24. // do something 25. Toast.makeText(getActivity(), item.title, Toast.LENGTH_SHORT).show(); 26. } 27. }