Friday, 31 July 2015

Gridview in Android

Gridview is ViewGroup that displays items in two-dimensional, scrollable grid. The grid items are automatically inserted to the layout using ListAdapter.

In a simple meaning you can display items with grid. So your all items looks like same in your layout.

Here I display multiple images in GridView. When you click on any image it will display as a large image into Imageview.

So you can learn two things using this post. First is use of gridview and second is display selected item in other activity. 

Sample Code:

File: grid_layout.xml

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


</GridView>

File: AndroidGridLayoutActivity.java

GridView gridView = (GridView) findViewById(R.id.grid_view);

// Instance of ImageAdapter Class
gridView.setAdapter(new ImageAdapter(this));

/**
 * On Click event for Single Gridview Item
 * */
gridView.setOnItemClickListener(new OnItemClickListener() 
{
       @Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) 
{
// Sending image id to FullScreenActivity
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
// passing array index
i.putExtra("id", position);
startActivity(i);
}

});

Output:























Download Source Code : AndroidGridviewLayout

Happy Coding...:-)

No comments:

Post a Comment