Search code examples
javaandroidonclickimage-galleryandroid-gallery

Gallery image changes when clicked


When an image in an Android gallery is clicked, I need it to change to another image.

I'm using an Imageadapter to set up an array of images in the gallery, with an onItemClickListener that, for now, toasts a message - I need that onItemClick to change the image in the gallery to another image outside of the Imageadapter array.

Here is the Gallery code:

    Gallery ga = (Gallery)findViewById(R.id.Gallery01);  
    ga.setAdapter(new ImageAdapter(this));  

    imageView = (ImageView)findViewById(R.id.ImageView01);
    ga.setOnItemClickListener(new OnItemClickListener() {

        //@Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            Toast.makeText(getBaseContext(), 
                    "You have selected icon " + (arg2+1) + " in Lifestyles", 
                    Toast.LENGTH_SHORT).show();
        }

    });

And here is the ImageAdapter:

public class ImageAdapter extends BaseAdapter {

private Context ctx;
int imageBackground;

public ImageAdapter(Context c) {  
    ctx = c;
}

//@Override
public int getCount() {

    return pics.length;
}

//@Override
public Object getItem(int arg1) {

    return arg1;
}

//@Override
public long getItemId(int arg0) {

    return arg0;
}

//@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {   
    ImageView iv = new ImageView(ctx);
    iv.setImageResource(pics[arg0]);
    iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
    iv.setLayoutParams(new Gallery.LayoutParams(135,135));
    iv.setBackgroundResource(imageBackground);
    return iv;
}

private Integer[] pics = {     
        R.drawable.icon_0,
        R.drawable.icon_1,
        R.drawable.icon_2,
        R.drawable.icon_3,
};

}


Solution

  • I guess it would be better to work that in the getView itself, Have the view invalidate in onItemClick and then change the image in the getView