Grid Layout - Android Example

DOWNLOAD CODE

Related Examples

In this example making a grid view with very basic example.

GridView give flexibility to arrange components in a two-dimensional scrolling grid.

 

activity_grid_view.xml  :

 

   <RelativeLayout xmlns:tools="http://schemas.android.com/tools"
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
        
                    <GridView
                        android:id="@+id/gridview1"
                        android:layout_width="fill_parent"
                        android:layout_height="fill_parent"
                        android:columnWidth="50dp"
                        android:gravity="center"
                        android:numColumns="auto_fit"
                        android:stretchMode="columnWidth" >
                 
                    </GridView>
         
        
    </RelativeLayout>

 

 

GridViewAndroidExample.java  :

 

public class GridViewAndroidExample 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.activity_grid_view);
             
                    gridView = (GridView) findViewById(R.id.gridview1);  
             

                  // Create adapter to set value for grid view
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                            android.R.layout.simple_list_item_1, numbers);
             
                    gridView.setAdapter(adapter);
             
                    gridView.setOnItemClickListener(new OnItemClickListener() {


                        @Override
                        public void onItemClick(AdapterView<?> parent, View v,
                            int position, long id) {


                           Toast.makeText(getApplicationContext(),
                            ((TextView) v).getText()  , Toast.LENGTH_SHORT).show();


                        }
                    });
             
                }
     
    }