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

Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdfImplementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdfVictor Lopez
 
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAlluxio, Inc.
 
OpenChain @ LF Japan Executive Briefing - May 2024
OpenChain @ LF Japan Executive Briefing - May 2024OpenChain @ LF Japan Executive Briefing - May 2024
OpenChain @ LF Japan Executive Briefing - May 2024Shane Coughlan
 
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdfMicrosoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdfQ-Advise
 
how-to-download-files-safely-from-the-internet.pdf
how-to-download-files-safely-from-the-internet.pdfhow-to-download-files-safely-from-the-internet.pdf
how-to-download-files-safely-from-the-internet.pdfMehmet Akar
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfkalichargn70th171
 
How to pick right visual testing tool.pdf
How to pick right visual testing tool.pdfHow to pick right visual testing tool.pdf
How to pick right visual testing tool.pdfTestgrid.io
 
SQL Injection Introduction and Prevention
SQL Injection Introduction and PreventionSQL Injection Introduction and Prevention
SQL Injection Introduction and PreventionMohammed Fazuluddin
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...Alluxio, Inc.
 
KLARNA - Language Models and Knowledge Graphs: A Systems Approach
KLARNA -  Language Models and Knowledge Graphs: A Systems ApproachKLARNA -  Language Models and Knowledge Graphs: A Systems Approach
KLARNA - Language Models and Knowledge Graphs: A Systems ApproachNeo4j
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAlluxio, Inc.
 
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Andrea Goulet
 
Workforce Efficiency with Employee Time Tracking Software.pdf
Workforce Efficiency with Employee Time Tracking Software.pdfWorkforce Efficiency with Employee Time Tracking Software.pdf
Workforce Efficiency with Employee Time Tracking Software.pdfDeskTrack
 
What need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java DevelopersWhat need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java DevelopersEmilyJiang23
 
Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Soroosh Khodami
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfmbmh111980
 
A Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data MigrationA Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data MigrationHelp Desk Migration
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Krakówbim.edu.pl
 

Recently uploaded (20)

Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdfImplementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
 
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
 
OpenChain @ LF Japan Executive Briefing - May 2024
OpenChain @ LF Japan Executive Briefing - May 2024OpenChain @ LF Japan Executive Briefing - May 2024
OpenChain @ LF Japan Executive Briefing - May 2024
 
5 Reasons Driving Warehouse Management Systems Demand
5 Reasons Driving Warehouse Management Systems Demand5 Reasons Driving Warehouse Management Systems Demand
5 Reasons Driving Warehouse Management Systems Demand
 
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdfMicrosoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
 
how-to-download-files-safely-from-the-internet.pdf
how-to-download-files-safely-from-the-internet.pdfhow-to-download-files-safely-from-the-internet.pdf
how-to-download-files-safely-from-the-internet.pdf
 
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdfA Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
A Comprehensive Appium Guide for Hybrid App Automation Testing.pdf
 
How to pick right visual testing tool.pdf
How to pick right visual testing tool.pdfHow to pick right visual testing tool.pdf
How to pick right visual testing tool.pdf
 
SQL Injection Introduction and Prevention
SQL Injection Introduction and PreventionSQL Injection Introduction and Prevention
SQL Injection Introduction and Prevention
 
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
AI/ML Infra Meetup | Improve Speed and GPU Utilization for Model Training & S...
 
KLARNA - Language Models and Knowledge Graphs: A Systems Approach
KLARNA -  Language Models and Knowledge Graphs: A Systems ApproachKLARNA -  Language Models and Knowledge Graphs: A Systems Approach
KLARNA - Language Models and Knowledge Graphs: A Systems Approach
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in Michelangelo
 
Top Mobile App Development Companies 2024
Top Mobile App Development Companies 2024Top Mobile App Development Companies 2024
Top Mobile App Development Companies 2024
 
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
Entropy, Software Quality, and Innovation (presented at Princeton Plasma Phys...
 
Workforce Efficiency with Employee Time Tracking Software.pdf
Workforce Efficiency with Employee Time Tracking Software.pdfWorkforce Efficiency with Employee Time Tracking Software.pdf
Workforce Efficiency with Employee Time Tracking Software.pdf
 
What need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java DevelopersWhat need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java Developers
 
Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
 
A Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data MigrationA Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data Migration
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Kraków
 

Featured

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 HubspotMarius Sescu
 
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 ChatGPTExpeed Software
 
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 EngineeringsPixeldarts
 
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 HealthThinkNow
 
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.pdfmarketingartwork
 
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 2024Neil Kimberley
 
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)contently
 
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 2024Albert Qian
 
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 InsightsKurio // The Social Media Age(ncy)
 
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 2024Search Engine Journal
 
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 summarySpeakerHub
 
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 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 Tessa Mero
 
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 IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
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 managementMindGenius
 
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...RachelPearson36
 

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