Software Development Exam  >  Software Development Notes  >  GridView in Android with Example

GridView in Android with Example - Software Development PDF Download

GridView in Android with Example

Last Updated: 30 Aug, 2022

A GridView is a type of AdapterView that displays items in a two-dimensional scrolling grid. Items are inserted into this grid layout from a database or from an array. The adapter is used for displaying this data; the setAdapter() method is used to link the adapter with GridView. The main role of the adapter in GridView is to retrieve data from a database or array and place each piece of data in a suitable item to be shown in GridView. This project involves implementation using Java and Kotlin Programming Language for Android.

setAdapter()

Java and Kotlin Programming Language for Android.

GridView in Android with Example - Software Development

XML Attributes of GridView

  • android:numColumns: This attribute determines the number of columns to display in the grid.
  • android:horizontalSpacing: This attribute defines the spacing between two columns of the GridView.
  • android:verticalSpacing: This attribute specifies the spacing between two rows of the GridView.
  • Step By Step Implementation

    • Step 1: Creating a New Project in Android Studio

      To initiate a new project in Android Studio, follow the steps outlined below:

      • Refer to guidelines on creating a new project in Android Studio, provided in Java and Kotlin.

      By following these steps, you can set up a new project in Android Studio using Java or Kotlin programming languages.

    • Step 2: Adding the Required Dependencies

      To enhance your project, include the Google Repository in your settings.gradle file.

      Ensure to synchronize the project after making these changes.

    • Step 3: Working with the XML Files

      When working with XML files, particularly the activity_main.xml file representing the project's user interface:

      • Explore the code snippet for the activity_main.xml file provided below for better comprehension.

      Make necessary modifications in the activity_main.xml file to tailor the UI as needed.

It is pivotal to follow these steps diligently to ensure the successful execution of your Android Studio project.

XML Code Snippet for activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity">
<GridView android:id="@id/idGVcourses" android:layout_width="match_parent" android:layout_height="match_parent" android:horizontalSpacing="6dp" android:numColumns="2" android:verticalSpacing="6dp" />

Ensure that you create an XML layout file for each item displayed in the GridView. This can be achieved by following these steps:

  • Create a new XML file for each grid item within the GridView.
  • Navigate to app > res > layout, right-click, select Layout Resource File, and name the file as card_item.

Refer to the code snippet provided for the card_item.xml file for a better understanding of the structure.

Creating a Card Layout in Android

  • Access the layout resource file by navigating to app > res > layout and right-clicking to create a new layout resource file named card_item.xml.
  • Within the XML file, implement a Card Layout using the androidx.cardview.widget.CardView component.
  • Set the attributes for the CardView element:
    • Layout width to match_parent and height to 120dp.
    • Set the layout gravity to center and margin to 5dp.
    • Define the card's corner radius and elevation using app:cardCornerRadius and app:cardElevation respectively.
  • Enclose the CardView within a LinearLayout with vertical orientation for proper arrangement.
  • Add an ImageView for displaying an image and a TextView for text content.
  • Ensure that the ImageView has a width and height of 100dp and the source is set to a specific image resource.
  • Set the TextView's width to match the parent, with text aligned at the center.

Example:

For instance, when creating a course display card, you can use the ImageView to show the course icon and the TextView to display the course name.

Explanation of XML Implementation

  • Define the namespaces for Android and app using the appropriate URLs within the XML file.
  • Implement the structure of the Card Layout using XML tags like androidx.cardview.widget.CardView.
  • Specify attributes such as layout width, height, gravity, margin, corner radius, and elevation for the CardView.
  • Utilize a LinearLayout to contain the ImageView and TextView elements within the CardView.

Step 5: Create a Model Class for Storing Data

Step 5: Create a Model Class for Storing Data

When you are working on Android app development, specifically with GridView items, you need a Model Class to handle the data for each item. This Model Class, in Java or Kotlin, manages the information associated with every GridView item.

To create a Model Class named CourseModel, follow these steps:

  • Navigate to app > java > your apps package name.
  • Right-click and select New > Java Class.
  • Name your Java/Kotlin Class file as CourseModel.

Below is a snippet of the code for the CourseModel:

public class CourseModel {   // String course_name for storing the course name   // and imgid for storing the image ID.   private String course_name;   private int imgid;   public CourseModel(String course_name, int imgid) {     this.course_name = course_name;     this.imgid = imgid;   }   public String getCourse_name() {     return course_name;   }   public void setCourse_name(String course_name) {     this.course_name = course_name;   }   public int getImgid() {     return imgid;   }   public void setImgid(int imgid) {     this.imgid = imgid;   } }

Make sure to define the necessary attributes and methods within your CourseModel to effectively manage and retrieve data for your GridView items.

CourseModel Class

  • The CourseModel class is designed to hold data about a course, including the course name and an image ID.
  • This class includes methods to retrieve and set the course name and image ID.
  • For example, the getCourse_name() method returns the name of the course as a String.
  • The setCourse_name(course_name: String) method allows setting the course name.
  • Similarly, methods like getImgid() and setImgid(imgid: Int) handle the image ID.
  • Step 6: Create an Adapter Class

  • An Adapter Class is essential for populating data from the CourseModel class into each item displayed in a GridView.
  • To create an Adapter Class, you need to follow these steps:
  • Go to the app > java > apps package and right-click on it.
  • Then, click on New > Java Class and name your Java Class file as CourseGVAdapter.
  • Below is the code for the CourseGVAdapter file:
  • CourseGVAdapter Class

  • The CourseGVAdapter class extends ArrayAdapter<CourseModel> to adapt the data for display.
  • It overrides the getView() method to customize how each item in the GridView is displayed.
  • The getView() method inflates the layout for each item and binds data from the CourseModel to the views.
  • It sets the course name and image based on the position in the GridView.
  • Below is a snippet of the CourseGVAdapter class:
  • import android.content.Context;import android.view.LayoutInflater;
    import android.view.View;import android.view.ViewGroup;
    import android.widget.ArrayAdapter;import android.widget.ImageView;
    import android.widget.TextView;import androidx.annotation.NonNull;
    import androidx.annotation.Nullable;import java.util.ArrayList;
  • The CourseGVAdapter constructor takes a Context and an ArrayList of CourseModel objects.
  • The getView() method inflates the layout for each item if needed and binds data to the views.
  • It sets the course name and image for each item in the GridView.
  • Understanding CourseGVAdapter Class in Android

    • In Android, the CourseGVAdapter class is utilized for adapting the course data to be displayed in a GridView.
    • This class extends ArrayAdapter and is responsible for handling how the data is presented in the UI.

    Key Components of CourseGVAdapter Class

    • The CourseGVAdapter class requires several key components to function effectively:
      • android.content.Context: This component provides information about the application's environment.
      • android.view.LayoutInflater: Used to inflate the layout of each item in the GridView.
      • android.view.View: Represents the basic building block for user interface elements.
      • android.view.ViewGroup: The parent view that holds the child views.

    Understanding the getView Method

    • The getView method is crucial in the CourseGVAdapter class for rendering each item in the GridView.
    • It takes parameters such as position, convertView, and parent to determine how each item should be displayed.

    Working with CourseModel Data

    • The CourseModel class holds information about a specific course, including its name and image ID.
    • Methods like getCourse_name() and getImgid() are used to retrieve this data for display.

    Example Usage of CourseGVAdapter Class

    • Let's consider an example where a list of courses is displayed in a GridView.
    • Each item in the GridView will show the course name (courseTV) and an image representing the course (courseIV).

    Implementing the Adapter

    • When implementing the CourseGVAdapter, ensure that it properly inflates the layout for each item and sets the course name and image.
    • Make sure to handle null cases for convertView and retrieve the correct CourseModel for the current position.

    Visual Representation in a GridView

    GridView in Android with Example - Software DevelopmentCourse Name: Introduction to Android Development
    • Step 7: Working with the MainActivity File

      • Accessing MainActivity File: Navigate to the MainActivity File and review the provided code snippet. This code snippet pertains to the MainActivity File, crucial for Android app development.
      • MainActivity Class: Inside the MainActivity class, essential components like GridView and AppCompatActivity are imported to facilitate the application's functionality.
      • Code Breakdown:
        • Upon onCreate() execution, the layout file "activity_main" is set for display.
        • The GridView named "coursesGV" is initialized and associated with the layout element "idGVcourses".
        • An ArrayList named "courseModelArrayList" is created to store CourseModel objects.
        • CourseModel objects for various courses like "DSA," "Java," "C," "Python," and "Javascript" are added to the ArrayList.
        • A custom adapter "CourseGVAdapter" is employed to set the adapter for the courses GridView.
      • Functionality:
        • The MainActivity File plays a pivotal role in initializing the app layout and populating the GridView with course information.
        • Through the code provided, courses like Data Structures and Algorithms (DSA), Java, C, Python, and Javascript are dynamically displayed in the app interface.
        • This code segment exemplifies how to bind data to a GridView using an adapter for effective content presentation.

    Explanation of Android Code

    • Import Statements:
      • android.os.Bundle: Represents a mapping from String keys to various Parcelable values.
      • android.widget.GridView: Displays items in a two-dimensional, scrollable grid.
      • androidx.appcompat.app.AppCompatActivity: Base class for activities that use the support library action bar features.
    • MainActivity Class:
      • Initialization: Inheriting from AppCompatActivity, MainActivity contains a GridView variable 'coursesGV' and overrides the 'onCreate' method.
      • Layout Setup: Sets the content view to 'activity_main' layout resource.
      • Data Population: Creates a list of CourseModel objects and adds course information along with corresponding images.
      • Adapter Setup: Utilizes CourseGVAdapter to populate the GridView with the course data.

    Detailed Code Explanation

    lateinit var coursesGV: GridViewDeclares a GridView variable 'coursesGV' without initializing it immediately.
    override fun onCreate(savedInstanceState: Bundle?)Overrides the onCreate method to initialize the activity when it is first created.
    setContentView(R.layout.activity_main)Sets the activity content from a layout resource.
    coursesGV = findViewById(R.id.idGVcourses)Finds the GridView with the specified id from the layout.
    courseModelArrayList.add(CourseModel("DSA", R.drawable.ic_gfglogo))Adds a CourseModel object for the "DSA" course with a specific drawable image.
    val adapter = CourseGVAdapter(this, courseModelArrayList)Creates an adapter to populate the GridView with the course data.
    coursesGV.adapter = adapterSets the adapter for the GridView to display the course information.

    Output:

    GridView in Android with Example - Software Development

    Please Login to comment...

    LoginLike
    • Paraphrased Information:

      • GridView in Android:

        A GridView in Android is a view group that displays items in a two-dimensional scrolling grid. It is used to display items in a scrollable grid format.

      • Functionality:

        It allows users to scroll through items horizontally and vertically, providing a flexible way to display a collection of items.

      • Customization:

        Developers can customize the appearance of items in the grid view by defining custom adapters and layouts for the grid cells.

      • Example:

        For instance, a music app can use a GridView to display album covers in a grid layout, allowing users to scroll through and select albums.

    The document GridView in Android with Example - Software Development is a part of Software Development category.
    All you need of Software Development at this link: Software Development

    Top Courses for Software Development

    Download as PDF
    Explore Courses for Software Development exam

    Top Courses for Software Development

    Signup for Free!
    Signup to see your scores go up within 7 days! Learn & Practice with 1000+ FREE Notes, Videos & Tests.
    10M+ students study on EduRev
    Related Searches

    Extra Questions

    ,

    study material

    ,

    shortcuts and tricks

    ,

    Summary

    ,

    Important questions

    ,

    GridView in Android with Example - Software Development

    ,

    Exam

    ,

    Free

    ,

    Semester Notes

    ,

    GridView in Android with Example - Software Development

    ,

    Sample Paper

    ,

    ppt

    ,

    video lectures

    ,

    mock tests for examination

    ,

    Viva Questions

    ,

    GridView in Android with Example - Software Development

    ,

    Objective type Questions

    ,

    MCQs

    ,

    practice quizzes

    ,

    pdf

    ,

    past year papers

    ,

    Previous Year Questions with Solutions

    ;