Site icon ParallelCodes

How to bind Android Gridview from ArrayAdapter List

How to Display data in Android GridView using ArrayAdapter? Let’s see.

In this post we will see how we can bind our Android Gridview using ArrayAdapter and List<String>. The example is pretty simple and straight-forward.

Bind Android Gridview from ArrayAdapter:

Edit your Android activity_main.xml:

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#d4dafc"
android:orientation="vertical">

<GridView
android:id="@+id/gridCompanies"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="0dp"
android:layout_marginTop="2dp"
android:background="#d4dafc"
android:gravity="center"
android:horizontalSpacing="2dp"
android:numColumns="3"
android:stretchMode="columnWidth"
android:verticalSpacing="2dp" />

</LinearLayout>

Create a new layout file named gridcell.xml and edit it as below. This will work as a layout template for our Android Gridview.

gridcell.xml:

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="#fff"
android:textStyle="bold"
android:textColor="#000"
android:layout_gravity="center_horizontal|center_vertical"
android:gravity="center_horizontal|center_vertical"/>

This will how the GridView will look like:

And your Android MainActivity.java as below:

MainActivity.java:

package com.my.androidgridview;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.GridView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

GridView gridCompanies;
String[] strCompanies = new String[]{"BMW", "MERCEDES", "HONDA", "TATA", "GENERAL MOTORS", "TOYOTA",
"BAJAJ", "FORD", "VOLKSWAGEN", "FERRARI", "BENTLEY", "LG", "SAMSUNG", "APPLE", "NOKIA", "ACER", "LENOVO", "DELL",
"HP", "MOTOROLA", "VIVO", "OPPO", "OKAY!"};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

gridCompanies = findViewById(R.id.gridCompanies);

List<String> values = new ArrayList<String>();
for (int y = 0; y < strCompanies.length; y++) {
values.add(strCompanies[y]);
}
gridCompanies.setAdapter(new ArrayAdapter<String>(this, R.layout.gridcell, values));
}
}

Below is the result:

Also see:

How you can fill Android Gridview from MS SQL server database tables using jtds library without any web api:

How to fill data in Android Gridview using MS SQL Database?

How you can fill Android Gridview using local SQLite database table:
Android GridView Binding from SQLite Database.

Thanks. Happy Coding 🙂 🙂

 


Exit mobile version