Friday, May 4, 2012

Normal GridView example


Normal GridView example

Display characters from A to Z in GridView layout. Quite simple, it should be sef-explanatory.
1.1 Android Layout file – res/layout/main.xml
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridView1"
    android:numColumns="auto_fit"
    android:gravity="center"
    android:columnWidth="50dp"
    android:stretchMode="columnWidth"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
 
</GridView>
1.2 Activity
package com.mkyong.android;
 
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
 
public class GridViewActivity extends Activity {
 
 GridView gridView;
 
 static final String[] numbers = new String[] { 
   "A", "B", "C", "D", "E",
   "F", "G", "H", "I", "J",
   "K", "L", "M", "N", "O",
   "P", "Q", "R", "S", "T",
   "U", "V", "W", "X", "Y", "Z"};
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
 
  setContentView(R.layout.main);
 
  gridView = (GridView) findViewById(R.id.gridView1);
 
  ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
    android.R.layout.simple_list_item_1, numbers);
 
  gridView.setAdapter(adapter);
 
  gridView.setOnItemClickListener(new OnItemClickListener() {
   public void onItemClick(AdapterView<?> parent, View v,
    int position, long id) {
      Toast.makeText(getApplicationContext(),
    ((TextView) v).getText(), Toast.LENGTH_SHORT).show();
   }
  });
 
 }
 
}
1.3 Demo
android grid view example

No comments: