GridView

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. 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.

1. GridViewAndroidExample.java

package com.tutorialsee.gridview;

import com.tutorialsee.gridview.R;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

public class GridViewAndroidExample extends Activity {

GridView gridView;
static final String[] numbers = new String[] {
"GridView", "Android", "IOS", "Windows", "Example",
"Design", "Cardivew", "ListView", "One", "Tow",
"Three", "Four", "Five", "Simple", "Multiple",
"Libraries", "Private", "Drawable", "Layout", "Values"};

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_grid_view);

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() {
@Override
public void onItemClick(AdapterView<?> parent, View v,int position, long id) {
Toast.makeText(getApplicationContext(),((TextView) v).getText(), Toast.LENGTH_SHORT).show();
}
});
}
}

2. activity_grid_view.xml

<RelativeLayout xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <GridView
        android:id="@+id/gridview1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:columnWidth="130dp"
        android:gravity="center"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth" >
    </GridView>

</RelativeLayout>