Create alphabet list in Android using GridView


We will build a trivial android app that create alphabet list using GridView. Fyi, Gridview is under ViewGroup that contains several View. I use Android 2.3.3 in this example. So, we can start create a new project called “Demo” and use “MainActivity” as main class.

src/com/yodi/demo/MainActivity.java

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.yodi.demo;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        // Generate alphabet
        String[] numbers = new String[26];
        char letter;
        int i;
       
        for(letter=’a’, i=0; letter <=’z’; letter++, i++) {
            numbers[i] = String.valueOf(letter);
        }
       
        // Get gridview layout from XML
        GridView gridView = (GridView) findViewById(R.id.gridview);
       
        // Set Adapter to connecting between context data and layout
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, numbers);
       
        // Set gridview using array adapter
        gridView.setAdapter(adapter);
       
        // Create handler for clicked item action
        gridView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                Toast.makeText(MainActivity.this, "" + position, Toast.LENGTH_SHORT).show();
            }
        });
    }

}

Then, the last thing we need to create is the layout :

/res/layout/activity_main.xml

1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridview"
    android:numColumns="auto_fit"
    android:gravity="center"
    android:columnWidth="50dp"
    android:stretchMode="columnWidth"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
</GridView>

And that’s it. Now you can compile your code into Android and you should see this :

We’re ready for the next examples! 😀

Fyi, you can grab the code from my github: https://github.com/yodiaditya/android


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.