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
An adapter actually bridges between UI components and the data source that fill data into UI Component. Adapter can be used to supply the data to like spinner, list view, grid view etc.
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.
We had learn Android ListView in last tutorial, this tutorial is similar as ListView tutorial.
Following are the important attributes specific to GridView:
Attribute | Attribute |
---|---|
android:id | This is the ID which uniquely identifies the layout. |
android:columnWidth | This specifies the fixed width for each column. This could be in px, dp, sp, in, or mm. |
android:gravity | Specifies the gravity within each cell. Possible values are top, bottom, left, right, center, center_vertical, center_horizontal etc. |
android:horizontalSpacing | Defines the default horizontal spacing between columns. This could be in px, dp, sp, in, or mm. |
android:numColumns | Defines how many columns to show. May be an integer value, such as "100" or auto_fit which means display as many columns as possible to fill the available space. |
android:stretchMode | Defines how columns should stretch to fill the available empty space, if any. This must be either of the values − -> none: Stretching is disabled. -> spacingWidth: The spacing between each column is stretched. -> columnWidth: Each column is stretched equally. -> spacingWidthUniform: The spacing between each column is uniformly stretched. |
android:verticalSpacing | Defines the default vertical spacing between rows. This could be in px, dp, sp, in, or mm. |
In this example i will be demonstrating how to build simple Android GridView and Custom GridView. This article is about creating simple GridView with textViews and CustomGridView with textViews and Images.
Let’s get start by creating a project in Eclipse IDE.
1. Create a new project in Eclipse by navigating to File ⇒ New Android ⇒ Application Project and fill required details. (I kept my main activity name as MainActivity.java)
2. Open your your AndroidManifest.xml file and make your “MainActivity” as Launcher activity.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.simplegridview" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="22" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> |
3. Create a layout file for MainActivtiy.java under res ⇒ layout folder. I named the layout file as activity_main.xml. This will be your first launching activity layout.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" > <GridView android:id="@+id/gridView1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:numColumns="3" > </GridView> </RelativeLayout> |
4. Add the following code in MainActivity.java activity. In this following code we make a ArrayList and use Adapter for manages the data model and adapts it to the individual entries in the widget as done in ListView.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
package com.simplegridview; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.Toast; public class MainActivity extends ActionBarActivity { GridView gridview; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gridview = (GridView) findViewById(R.id.gridView1); // String Array for setting data over gridview String data[] = { "A", "B", "C", "D", "F", "G", "H", "I" }; // Array adapter for holding the data ArrayAdapter<String> adapter = new ArrayAdapter<String>( MainActivity.this, android.R.layout.simple_list_item_1, data); // Setting adapter over gridview gridview.setAdapter(adapter); // Notifying adapter adapter.notifyDataSetChanged(); // Setting click listener on items gridview.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<> parent, View view, int position, long id) { // Showing clicked item position Toast.makeText(MainActivity.this, "Clicked Position : " + position, Toast.LENGTH_SHORT) .show(); } }); } } |
5. Run the application and you will get the output as shown in video.
1. Create a new project in Eclipse by navigating to File ⇒ New Android ⇒ Application Project and fill required details. (I kept my main activity name as MainActivity.java)
2. Open your your AndroidManifest.xml file and make your MainActivity as Launcher activity and SingleImageActivity is second activity.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.customgridview" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="22" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.customgridview.SingleImageActivity" > </activity> </application> </manifest> |
3. Create a layout file for MainActivtiy.java under res ⇒ layout folder. I named the layout file as activity_main.xml. This will be your first launching activity layout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" > <GridView android:id="@+id/gridView1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:horizontalSpacing="5dp" android:numColumns="2" android:gravity="center" android:stretchMode="columnWidth" android:verticalSpacing="5dp" > </GridView> </RelativeLayout> |
4. Create a layout file for custom views for gridview under res ⇒ layout folder. I named the layout file as customview.xml. This will be your custom layout for gridview.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="5dp" android:padding="5dp" > <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:adjustViewBounds="true" android:scaleType="centerCrop" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|center" android:background="#AA000000" android:gravity="center" android:padding="2dp" android:textColor="#ffffff" /> </FrameLayout> |
5. Create a Items.java class for setting and getting gridview items from it. This class works as getter and setter for gridview items.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.customgridview; public class Items { String title; Integer image; // Setter for Gridview public Items(String title, Integer image) { this.title = title; this.image = image; } // Getter for Gridviews public String getTitle() { return title; } public Integer getImages() { return image; } } |
6. Create a CustomGridViewAdapter.java class for custom gridview adapter for inflating custom view over gridView.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
package com.customgridview; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; public class CustomGridViewAdapter extends BaseAdapter { ArrayList<Items> arrayList; LayoutInflater inflater; ViewHolder holder = null; public CustomGridViewAdapter(Context context, ArrayList<Items> arrayList) { this.arrayList = arrayList; this.inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { // TODO Auto-generated method stub return arrayList.size(); } @Override public Object getItem(int pos) { // TODO Auto-generated method stub return arrayList.get(pos); } @Override public long getItemId(int pos) { // TODO Auto-generated method stub return pos; } @Override public View getView(int pos, View view, ViewGroup root) { if (view == null) { view = inflater.inflate(R.layout.customview, root, false); holder = new ViewHolder(); holder.image = (ImageView) view.findViewById(R.id.imageView); holder.text = (TextView) view.findViewById(R.id.textView); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } // Setting image and title from arraylist holder.image.setBackgroundResource(arrayList.get(pos).getImages()); holder.text.setText(arrayList.get(pos).getTitle()); return view; } // View holder class to hold the views public class ViewHolder { ImageView image; TextView text; } } |
7. Add the following code in MainActivity.java activity. In this following code we learn how to use custom adapter in gridview and set custom gridview over adapter.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
package com.customgridview; import java.util.ArrayList; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.Toast; public class MainActivity extends ActionBarActivity { GridView grid; // String array for image titles private static final String title[] = { "Cupcake", "Donut", "Eclair", "Froyo", "Gingerbread", "HoneyComb" }; // Integer array for drawable images private static final Integer Images[] = { R.drawable.cupcake, R.drawable.donut, R.drawable.eclair, R.drawable.froyo, R.drawable.gingerbread, R.drawable.honeycomb }; ArrayList<Items> arrayList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); grid = (GridView) findViewById(R.id.gridView1); // Array list for storing data in Items class arrayList = new ArrayList<Items>(); // For loop to add data in array list for (int i = 0; i < Images.length; i++) { arrayList.add(new Items(title[i], Images[i])); } // Setting data in custom adapter CustomGridViewAdapter adapter = new CustomGridViewAdapter( MainActivity.this, arrayList); grid.setAdapter(adapter); adapter.notifyDataSetChanged(); grid.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<> parent, View view, int pos, long id) { // Starting a new activity and passing image id Intent in = new Intent(MainActivity.this, SingleImageActivity.class); in.putExtra("image", arrayList.get(pos).getImages()); startActivity(in); } }); } } |
8. Create a layout file for single imageview under res ⇒ layout folder. I named the layout file as singleimageactivity.xml.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:gravity="center" android:layout_height="fill_parent" > <ImageView android:id="@+id/singleImage" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:adjustViewBounds="true" android:scaleType="centerCrop" /> </LinearLayout> |
9. Create a SingleImageActivity.java class for showing single image in activity and add the following code to it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.customgridview; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.widget.ImageView; public class SingleImageActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.singleimageactivity); // Getting Intent from MainActivity and storing in int variable int imagePath = getIntent().getIntExtra("image", 0); ImageView image = (ImageView) findViewById(R.id.singleImage); // Setting imagePath to image image.setBackgroundResource(imagePath); } } |
10. Run the application and you will get the output as shown in video and you are done.
Thanks. 🙂
Subscribe to us and get the latest news.