Thursday, January 2, 2014

Gridview in android / Gridview example in android / Grid layout in android

In res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/gridview"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:columnWidth="90dp" <!-- coloumn width  -->
    android:numColumns="auto_fit" <!-- number of coloumn will be automatically -->
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center"

/>

Open HelloGridView.java and insert the following code for the onCreate() method:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    GridView gridview = (GridView) findViewById(R.id.gridview);
    gridview.setAdapter(new ImageAdapter(this));

    gridview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            Toast.makeText(HelloGridView.this, "" + position, Toast.LENGTH_SHORT).show();
        }
    });
}

ImageAdapter class which will feed the data to the gridview.

//here we have added a.jpg,b.jpg,c.jpg,d.jpg,e.jpg,f.jpg,g.jpg,h.jpg in the res/drawable folder

package com.example.test;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter {

private Context mContext;
private Integer[] mThumbIds = {
           R.drawable.a, R.drawable.b,
           R.drawable.c, R.drawable.d,
           R.drawable.e, R.drawable.f,
           R.drawable.g, R.drawable.h
   };

    public ImageAdapter(Context c) {
        mContext = c;
    }
@Override
public int getCount() {
// TODO Auto-generated method stub
        return mThumbIds.length;

}

@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}

@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView imageView;
        if (convertView == null) {  // if it's not recycled, initialize some attributes
            imageView = new ImageView(mContext);
            imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        } else {
            imageView = (ImageView) convertView;
        }

        imageView.setImageResource(mThumbIds[position]);
        return imageView;
}

}

No comments:

Post a Comment