Simple Gridview Example In Android – Source Code

In Android, GridView let you arranges components in a two-dimensional scrolling grid.

In this tutorial, we will show you Simple GridView examples :

Normal way, just display text in GridView layout.

Display Some Words GridView layout.

Step : 1 – Layout file – res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridView1"
    android:numColumns="auto_fit"
    android:gravity="center"
    android:columnWidth="50dp"
    android:stretchMode="columnWidth"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
 
</GridView>

Step : 2 – Activity


package com.mkyong.android;
 
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
 
public class GridViewActivity extends Activity {
 
	GridView gridView;
 
	static final String[] numbers = new String[] { 
			"Food", "Logo", "Face", "XBox", "Google",
			"Holly", "Left", "Simple", "Right", "Joy",
			"Lier", "Local", "Manothra", "Noise", "Output",
			"Police", "Quran", "Royal", "Swastik", "Toy",
			"Uranus", "Virtual", "Wait", "Xmaria", "Yellow", "Zogi"};
 
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
 
		setContentView(R.layout.main);
 
		gridView = (GridView) findViewById(R.id.gridView1);
 
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, numbers);
 
		gridView.setAdapter(adapter);
 
		gridView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v,
				int position, long id) {
			   Toast.makeText(getApplicationContext(),
				((TextView) v).getText(), Toast.LENGTH_SHORT).show();
			}
		});
 
	}
 
}

Enjoy Your Code.