Friday, January 16, 2015

How to data bind GridView with ArrayAdapter in Android

activity_main.xml

<GridView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/gridView"
    android:numColumns="3"
    android:verticalSpacing="8dp"
    android:horizontalSpacing="12dp"
    android:background="#F8F8FF"
    android:columnWidth="100dp">
    <!--content will be generate programmatically-->
</GridView>
MainActivity.java

package com.cfsuman.androidtutorials;

import android.os.Bundle;
import android.app.Activity;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import java.util.ArrayList;
import java.util.Arrays;


public class MainActivity extends Activity {

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

                // Get the context
                MainActivity context = this;

                // Get the widgets reference from XML layout
                GridView gridView = findViewById(R.id.gridView);

                //initializing a String array
                String[] array = new String[]{
                        "Red",
                        "Green",
                        "Blue",
                        "Yellow",
                        "Black",
                        "Pink",
                        "Magenta"
                };

                //initializing an ArrayList from array
                ArrayList<String> list = new ArrayList<>(
                        Arrays.asList(array)
                );

                //Data bind GridView with ArrayAdapter
                gridView.setAdapter(new ArrayAdapter<String>(
                        context,
                        android.R.layout.simple_list_item_1,
                        list)
                );
        }
}