Wednesday 29 August 2012

Android GridView tutorial and Example Code


GridView:

  • Contains a horizontally scrolling list of View objects, also often used with image icons; the user can select an item to perform some action upon.
Let's take Simple Example which shows the Grid of  TextView that will be display as grid on Screen and you can select on of them. 

The Layout of this app is as follows : main.xml 

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridView01"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:columnWidth="90dp"
    android:numColumns="2"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
    />


The Java file can be as follows.

 
package com.container;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class GridViewContainerActivity extends Activity {
    /** Called when the activity is first created. */
    GridView gv;
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        String [] colors= {"Red","Green","Blue","Pink","Gray"};
        gv=(GridView)findViewById(R.id.gridView01);
        
        ArrayAdapter<String> adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_gallery_item, colors);
        gv.setAdapter(adapter);
        gv.setNumColumns(3);
        gv.setBackgroundColor(Color.CYAN);
        gv.setGravity(Gravity.CENTER);
        gv.setOnItemClickListener(new OnItemClickListener() {

   public void onItemClick(AdapterView<?> myAdapter, View view, int myItemId,
     long myLang) {
    // TODO Auto-generated method stub
    
    String selectedItem=gv.getItemAtPosition(myItemId).toString();
  
    Toast.makeText(getApplicationContext(), selectedItem, 2).show();
   }
  });
    }
}

When you first run your app that will shown as follows.


 For example you select "Green" than following output will be displayed.

11 comments:

  1. This comment has been removed by the author.

    ReplyDelete