Pages

Saturday, September 8, 2012

Android Grid View Example


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
 
 
    <GridView
    android:id="@+id/grid"
    android:columnWidth="100px"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:stretchMode="columnWidth"
    android:gravity="center"
    android:numColumns="auto_fit"
    />

</LinearLayout>


set your Activity........

package adapter.grid;

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

public class GridAdapterEx extends Activity {
    
GridView gv;
String[] listcontent={"c","java","php","c++","jsp","c#","servlet","struts"
 
,"c","java","php","c++","jsp","c#","servlet","struts",
"c","java","php","c++","jsp","c#","servlet","struts"};
/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        
        gv=(GridView)findViewById(R.id.grid);
        ArrayAdapter<String> adapter
        = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,listcontent);
   gv.setOnItemClickListener(new OnItemClickListener() {

public void onItemClick(AdapterView<?> v0, View v1, int v2, long v3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),((TextView)v1).getText(),Toast.LENGTH_SHORT).show();
}

   
   
   });
        gv.setAdapter(adapter);
    }
}

1 comment:

  1. Thats very good and simple example indeed it helps in understanding the concept of gridview layout laying it's child views , you can find the one at
    Normal GridView and
    Customized GridView

    ReplyDelete