Thursday, September 15, 2011

GridView Demo with Text

GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid.

We are going to create a Grid View to show Text, where we can select each item via click.

so lets create simple app with default activity "GridViewActivity" and put this code inside it.
  
package com.rdc;

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 GridViewActivity extends Activity {
 
 GridView gridView;

 static final String[] numbers = new String[]{
  "A", "B", "C", "D",
  "E", "F", "G", "H",
 };
 
    @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(),
           "Selected: " +((TextView) v).getText(), 
           Toast.LENGTH_SHORT).show();
         }
        });        
   }
}

and the main.xml file is
  


 


out put is like this

No comments:

Post a Comment