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:id="@+id/grid_view"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:numColumns="3"
    android:verticalSpacing="2dp"
    android:horizontalSpacing="2dp"
    android:background="#ff5555"
    android:columnWidth="75dp"
    android:layout_margin="15dp"
    >
    <!--content will be generate programmatically-->
</GridView>
MainActivity.java code snippet

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

 //initializing a String array
 String[] array = new String[]{"one","two","three","four","five","six","seven"};
 //initializing an ArrayList from array
 List<String> list = new ArrayList<String>(Arrays.asList(array));

 //refer GridView from xml layout file
 GridView gd = (GridView) findViewById(R.id.grid_view);
 //data bind GridView with ArrayAdapter
 gd.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list));
}
Imported Class

import android.widget.ArrayAdapter;
import android.widget.GridView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
More android examples