Using GridView in ANDROID….

By | March 9, 2011

GridViews are those in which you can arrange elements in a two dimensional grid.
It is what you see in the gallery where images are arranged. Here images are arranged in a two dimensional grid.
Copy the below code and save it as “MyGridView.java”

[java]
package com.pack;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MyGridView extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gv = (GridView) findViewById(R.id.gridview);
gv.setAdapter(new ImageAdapter(this));
gv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
Toast.makeText(MyGridView.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
}
}

/********************************* End of MyGridView.java ****************************** **/
[/java]
Now create another file named “Images.java” and copy the below code to it.
[java]
package com.pack;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
lass="Apple-style-span" style="font-family: Times, ‘Times New Roman’, serif;">import android.widget.ImageView;
public class Images extends BaseAdapter {
private Context ctxt;
public Images (Context c) {
ctxt = c;
}
public int getCount() {
return Ids.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int pos) {
return 0;
}
public View getView(int pos, View convertView, ViewGroup parent) {
ImageView imgView;
if (convertView == null) {
imgView = new ImageView(mContext);
imgView.setLayoutParams(new GridView.LayoutParams(85, 85));
imgView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imgView.setPadding(8, 8, 8, 8);
} else {
imgView = (ImageView) convertView;
}
imgView.setImageResource(Ids[pos]);
return imgView;
}
private Integer[] Ids = {
R.drawable.img_2, R.drawable.img_3,
R.drawable.img_4, R.drawable.img_5,
R.drawable.img_6, R.drawable.img_7,
R.drawable.img_0, R.drawable.img_1,
R.drawable.img_2, R.drawable.img_3,
R.drawable.img_4, R.drawable.img_5,
R.drawable.img_6, R.drawable.img_7,
R.drawable.img_0, R.drawable.img_1,
R.drawable.img_2, R.drawable.img_3,
R.drawable.img_4, R.drawable.img_5,
R.drawable.img_6, R.drawable.img_7
};
}
/*********************************** End of Images.java**************************** **/
[/java]
Note: Please make sure that you have images named img_0 to img_7 in your res/drawable folder.
Please leave your valuable comments if this post was useful…..

Leave a Reply

Your email address will not be published. Required fields are marked *