A GridView in Android is a ViewGroup that displays items in a two-dimensional, scrollable grid. The grid items are automatically inserted into the layout using a ListAdapter. In this blog, we’ll learn how to use GridView in an Android app using Java.
Creating a GridView
To create a GridView, you first need to define it in your layout file:
<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:columnWidth="60dp"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"/>
Populating the GridView
To populate the GridView with data, you need to create an ArrayAdapter and set it to the GridView. Here’s how you can do it:
GridView gridView = findViewById(R.id.gridView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, new String[]{"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"});
gridView.setAdapter(adapter);
In the above code, new String[]{"Item 1", "Item 2", "Item 3", "Item 4", "Item 5"}
is an array of strings that you want to display in the GridView.
Handling GridView Clicks
To handle the click event on grid items, you need to set an OnItemClickListener
to the GridView:
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String selectedItem = (String) parent.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), "Clicked: " + selectedItem, Toast.LENGTH_SHORT).show();
}
});
In the above code, when an item is clicked, a Toast message is displayed showing the clicked item.