GridView sample program in Android
 


This sample android program shows you how to use GridView in Android. In this program a list is shown as a grid. When you click on the list, the selected item is shown on the text view. You can use this ArrayAdapter widget and the GridView object together with the onListItemClick() method to determine the selected index and process accordingly.

The GridViewDemo.java file is as follows:

package com.javasamples;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;


public class GridViewDemo extends Activity implements
		AdapterView.OnItemClickListener {

	TextView selection;
	String[] items = { "this", "is", "a", "really", "really2", "really3",
			"really4", "really5", "silly", "list" };

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.main);
		selection = (TextView) findViewById(R.id.selection);

		GridView gv = (GridView) findViewById(R.id.grid);

		ArrayAdapter<String> aa = new ArrayAdapter<String>(
				this,
				android.R.layout.simple_list_item_1, 
				items );

		gv.setAdapter(aa);
		gv.setOnItemClickListener(this);
	}

	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		selection.setText(items[position]);
	}
	
}// class


The output of this program will be as shown in the android emulator below.

The main.xml file in your res/layout folder is as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView
        android:id="@+id/selection"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ff0033cc"
	  android:textSize="14pt"
 	  android:textStyle="bold"
        
        />
    <GridView
        android:id="@+id/grid"
        android:background="#ff0000ff"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent"
        android:verticalSpacing="35px"
        android:horizontalSpacing="5px"
        android:numColumns="auto_fit"
        android:columnWidth="100px"
        android:stretchMode="columnWidth"
        android:gravity="center"
        />
</LinearLayout>
 
 
 
 
 
COPYRIGHT © 2017 java-samples.com. ALL RIGHTS RESERVED.