Download this project
MainActivity.java
package com.gridviewdemo;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
public class MainActivity extends ActionBarActivity {
GridView grid_view;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
grid_view = (GridView) findViewById(R.id.gridview);
grid_view.setAdapter(new ImageAdapter(this));
grid_view.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getBaseContext(), "You click on image "+arg2, Toast.LENGTH_LONG).show();
}
});
}
}
ImageAdapater.java
package com.gridviewdemo;
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 CTX;
private Integer image_id[] = {R.drawable.sample_0,
R.drawable.sample_1, R.drawable.sample_2,
R.drawable.sample_3,
R.drawable.sample_4,
R.drawable.sample_5,
R.drawable.sample_6,
R.drawable.sample_7
};
public ImageAdapter(Context CTX) {
this.CTX = CTX;
// TODO Auto-generated constructor stub
}
@Override
public int getCount() {
return image_id.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 arg0, View arg1, ViewGroup arg2) {
ImageView img;
if(arg1 == null)
{
img = new ImageView(CTX);
img.setLayoutParams(new GridView.LayoutParams(160,160));
img.setScaleType(ImageView.ScaleType.CENTER_CROP);
img.setPadding(8, 8, 8, 8);
}
else
{
img = (ImageView) arg1;
}
img.setImageResource(image_id[arg0]);
return img;
// TODO Auto-generated method stub
// return null;
}
}
activity_main.xml
<GridView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
>
</GridView>
Comments
Post a Comment