0% found this document useful (0 votes)
59 views10 pages

Android GridView Tutorial and Example

The document discusses Android GridView which displays items in a two-dimensional scrolling grid. It describes how GridView works with an adapter to populate data from a source and create views for each data entry. It provides attributes of GridView and examples of creating a GridView app to display images in a grid along with adding a sub-activity to view images fullscreen.

Uploaded by

html backup
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views10 pages

Android GridView Tutorial and Example

The document discusses Android GridView which displays items in a two-dimensional scrolling grid. It describes how GridView works with an adapter to populate data from a source and create views for each data entry. It provides attributes of GridView and examples of creating a GridView app to display images in a grid along with adding a sub-activity to view images fullscreen.

Uploaded by

html backup
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Android Grid View

Android GridView shows items in two-dimensional scrolling grid (rows & columns) and the grid items are not
necessarily predetermined but they automatically inserted to the layout using a ListAdapter

Grid view

An adapter actually bridges between UI components and the data source that fill data into UI Component.
Adapter can be used to supply the data to like spinner, list view, grid view etc.

The ListView and GridView are subclasses of AdapterView and they can be populated by binding them to an
Adapter, which retrieves data from an external source and creates a View that represents each data entry.

GridView Attributes
Following are the important attributes specific to GridView −

/
[Link] Attribute & Description

android:id
1
This is the ID which uniquely identifies the layout.

android:columnWidth
2
This specifies the fixed width for each column. This could be in px, dp, sp, in, or mm.

android:gravity
3 Specifies the gravity within each cell. Possible values are top, bottom, left, right, center, center_vertical,
center_horizontal etc.

android:horizontalSpacing
4
Defines the default horizontal spacing between columns. This could be in px, dp, sp, in, or mm.

android:numColumns
5 Defines how many columns to show. May be an integer value, such as "100" or auto_fit which means
display as many columns as possible to fill the available space.

android:stretchMode

Defines how columns should stretch to fill the available empty space, if any. This must be either of the
values −

6 none − Stretching is disabled.

spacingWidth − The spacing between each column is stretched.

columnWidth − Each column is stretched equally.

spacingWidthUniform − The spacing between each column is uniformly stretched..

android:verticalSpacing
7
Defines the default vertical spacing between rows. This could be in px, dp, sp, in, or mm.

Example

This example will take you through simple steps to show how to create your own Android application using
GridView. Follow the following steps to modify the Android application we created in Hello World Example chapter

/
Step Description

1 You will use Android studio IDE to create an Android application and name it as HelloWorld under a package
[Link] as explained in the Hello World Example chapter.

2 Modify the detault content of res/layout/activity_main.xml file to include GridView content with the self
explanatory attributes.

3 No need to change [Link], Android studio takes care of defaults strings which are placed at [Link]

4 Let's put few pictures in res/drawable-hdpi folder. I have put [Link], [Link], [Link],
[Link], [Link], [Link], [Link] and [Link].

5 Create a new class called ImageAdapter under a package [Link] that extends BaseAdapter.
This class will implement functionality of an adapter to be used to fill the view.

6 Run the application to launch Android emulator and verify the result of the changes done in the application.

Following is the content of the modified main activity file src/[Link]/[Link]. This
file can include each of the fundamental lifecycle methods.

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

GridView gridview = (GridView) findViewById([Link]);


[Link](new ImageAdapter(this));
}
}

Following will be the content of res/layout/activity_main.xml file −

<?xml version="1.0" encoding="utf-8"?>


<GridView xmlns:android="[Link]
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"
/>

Following will be the content of res/values/[Link] to define two new constants −


/
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">HelloWorld</string>
<string name="action_settings">Settings</string>
</resources>

Following will be the content of src/[Link]/[Link] file −

package [Link];

import [Link];

import [Link];
import [Link];

import [Link];
import [Link];
import [Link];

public class ImageAdapter extends BaseAdapter {


private Context mContext;

// Constructor
public ImageAdapter(Context c) {
mContext = c;
}

public int getCount() {


return [Link];
}

public Object getItem(int position) {


return null;
}

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) {
imageView = new ImageView(mContext);
[Link](new [Link](85, 85));
[Link]([Link].CENTER_CROP);
[Link](8, 8, 8, 8);
}
else
{
imageView = (ImageView) convertView;
}
[Link](mThumbIds[position]);
return imageView;
} /
// Keep all Images in array
public Integer[] mThumbIds = {
[Link].sample_2, [Link].sample_3,
[Link].sample_4, [Link].sample_5,
[Link].sample_6, [Link].sample_7,
[Link].sample_0, [Link].sample_1,
[Link].sample_2, [Link].sample_3,
[Link].sample_4, [Link].sample_5,
[Link].sample_6, [Link].sample_7,
[Link].sample_0, [Link].sample_1,
[Link].sample_2, [Link].sample_3,
[Link].sample_4, [Link].sample_5,
[Link].sample_6, [Link].sample_7
};
}

Let's try to run our modified Hello World! application we just modified. I assume you had created your AVD while
doing environment setup. To run the app from Android Studio, open one of your project's activity files and click

Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with
your setup and application, it will display following Emulator window −

/
Sub-Activity Example

Let's extend the functionality of above example where we will show selected grid image in full screen. To achieve
this we need to introduce a new activity. Just keep in mind for any activity we need perform all the steps like we
have to implement an activity class, define that activity in [Link] file, define related layout and finally
link that sub-activity with the main activity by it in the main activity class. So let's follow the steps to modify above
example −

Step Description

1 You will use Android studio IDE to create an Android application and name it as HelloWorld under a package
[Link] as explained in the Hello World Example chapter.

2 Create a new Activity class as [Link] under a package [Link] as shown


below.

3 Create new layout file for the new activity under res/layout/ folder. Let's name this XML file as single_view.xml.

4 Define your new activity in [Link] file using <activity.../> tag. An application can have one or more
activities without any restrictions.

5 Run the application to launch Android emulator and verify the result of the changes done in the application.

Following is the content of the modified main activity file src/[Link]/[Link]. This
file can include each of the fundamental life cycle methods.

package [Link];

import [Link];
import [Link];
import [Link];

import [Link];
import [Link];

import [Link];
import [Link];
import [Link];

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);

GridView gridview = (GridView) findViewById([Link]);


[Link](new ImageAdapter(this));

[Link](new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View v, int position, long id){
// Send intent to SingleViewActivity
Intent i = new Intent(getApplicationContext(), [Link]);
// Pass image index
[Link]("id", position);
/
startActivity(i);
}
});
}
}

Following will be the content of new activity file src/[Link]/[Link] file −

package [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class SingleViewActivity extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].single_view);

// Get intent data


Intent i = getIntent();

// Selected image id
int position = [Link]().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);

ImageView imageView = (ImageView) findViewById([Link]);


[Link]([Link][position]);
}
}

Following will be the content of res/layout/single_view.xml file −

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout
xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<ImageView android:id="@+id/SingleView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>

</LinearLayout>

Following will be the content of [Link] to define two new constants −

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="[Link]
package="[Link]">

<application
android:allowBackup="true"
/
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="[Link]"
android:label="@string/app_name" >

<intent-filter>
<action android:name="[Link]" />
<category android:name="[Link]" />
</intent-filter>

</activity>

<activity android:name=".SingleViewActivity"></activity>

</application>
</manifest>

Let's try to run our modified Hello World! application we just modified. I assume you had created your AVD while
doing environment setup. To run the app from Android studio, open one of your project's activity files and click

Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with
your setup and application, it will display following Emulator window −

/
Now if you click on either of the images it will be displayed as a single image, for example−

/
Kindly note above mentioned images have been taken from Android official website.

Common questions

Powered by AI

To modify an Android application to include a GridView, first modify the `activity_main.xml` layout file to include a GridView element. Define necessary attributes like `android:columnWidth`, `android:numColumns`, `android:verticalSpacing`, and `android:horizontalSpacing`. Next, place images or other resources to be displayed within `res/drawable-hdpi`. Implement an adapter class like `ImageAdapter` to populate the GridView. Finally, update the MainActivity to set this adapter to the GridView and test on an Android emulator .

Declaring all activities in AndroidManifest.xml is crucial as it enables the Android operating system to recognize and access the application's components. This declaration specifies configurations like activities, services, permissions, hardware features, and other essential data. Failure to declare activities can lead to runtime errors, as the OS would not be able to launch the activity due to it being unregistered in the system's knowledge base .

The `android:stretchMode` attribute determines how the columns of a GridView stretch to fill available space. It can take the values 'none', 'spacingWidth', 'columnWidth', or 'spacingWidthUniform'. 'None' disables stretching, 'spacingWidth' stretches the space between columns, 'columnWidth' stretches each column equally, and 'spacingWidthUniform' stretches the spacing uniformly between columns .

The layout parameters such as `android:columnWidth`, `android:verticalSpacing`, and `android:horizontalSpacing` directly influence the appearance and interactivity of the application UI. These parameters manage the dimensions and spacing of each item, affecting how content is perceived and interacted with. For instance, inadequate spacing can make tapping targets difficult, whereas excessive cell width may consume unnecessary screen space, leading to a cluttered UI. Properly configured parameters ensure a well-balanced layout that enhances user engagement and accessibility .

Setting `android:numColumns` to `auto_fit` allows the GridView to dynamically adjust the number of columns according to the available screen space. This flexibility enhances the responsiveness of the application, providing an optimal item display across various device sizes and orientations. It can improve user interaction by ensuring that all elements are visible and that screen real estate is efficiently utilized, although it may lead to inconsistent item sizing if screen sizes vary significantly .

Setting `android:gravity` in a GridView determines the alignment of items within each cell, which subsequently affects the overall appearance and usability of the UI. Values like 'center', 'left', 'right', 'top', or 'bottom' define where the contents will be positioned within each grid cell. Proper gravity alignment can enhance readability and aesthetic of the app interface, ensuring a consistent user experience .

The `android:numColumns` attribute defines the number of columns that a GridView should display. It can be set to a specific integer value or 'auto_fit'. 'Auto_fit' adjusts the number of columns dynamically to fill the available space, optimizing for different screen sizes and orientations .

A ListAdapter serves as a bridge between the UI components and the data source, enabling the efficient filling of data into UI components like GridView. It retrieves data from an external source and generates a View for each data item. This allows dynamic insertion of items without needing them to be predetermined .

The ImageAdapter class extends the BaseAdapter class, inheriting its structure and methods to function as an adapter that provides Views for each item in the grid. It overrides essential methods like `getCount`, `getItem`, `getItemId`, and `getView` to customize how data is presented within a GridView. This use of inheritance allows ImageAdapter to efficiently manage ImageView objects within the grid layout .

To add a new Activity in an Android application, first create a new Activity Java class in the project and define its layout in a separate XML file within the 'res/layout' directory. Then, declare the new Activity in the AndroidManifest.xml using the <activity> tag. This integration allows different parts of the application to manage user interactions and data presentation in separate, distinct workflows .

You might also like