Pages

Thursday, March 24, 2016

Android Simple Image Gallery

In this post we are going to use the gallery control t construct a simple image gallery.
the layout is like the previous post.

remeber that the Gallery control is populated by an adapter, so we will create a custom adapter that contains ImageViews to display the images.
our custom adapter must inherit from BaseAdapter class
package mina.android.GalleryDemo;

import java.util.ArrayList;
import java.util.List;

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

public class ImageAdapter extends BaseAdapter {
Context Con;
//array to hold the values of image resources
int [] Resources;
List views;

public ImageAdapter(Context con,int[] resources)
{
Con=con;
Resources=resources;
views=new ArrayList(resources.length);
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return Resources.length;
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return views.get(position);
//return position;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
//return views.get(position).getId();
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView img=new ImageView(Con);
img.setImageResource(Resources[position]);
views.add(img);

return img;
}

}


then in our activity onCreate Method:
int []res=new int[]{R.drawable.wc,R.drawable.wc2,R.drawable.wc3,R.drawable.wc4,R.drawable.wc5};
ItemsInGallery=res.length;
ImageAdapter imgAdapter=new ImageAdapter(this, res);
gallery.setAdapter(imgAdapter);

and that was our simple Image gallery.
download the application from here

Related Posts by Categories

0 comments:

Post a Comment