I have got an activity that shows a grid view with different images. When clicking on one of those images I want the clicked image to be the background image of another activity.
How can I do that?
This is my activity that shows the grid view:
public class HelloGridViewActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridView = (GridView) findViewById(R.id.gridview);
// Instance of ImageAdapter Class
gridView.setAdapter(new ImageAdapter(this));
/**
* On Click event for Single Gridview Item
* */
gridView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//WHAT SHALL I PUT HERE????
}
}
}
So, the poster didn’t (originally) specify exactly whether the other activity was to be opened immediately on click, or if the clicked item’s image just needed to be recorded for use later. The first problem seems more common to me, as in a
GridViewthat shows a set of image thumbnails. The user clicks on that, and a new Activity showing just that item’s information comes up. That thumbnail image maybe goes full screen. Anyway, maybe that’s not what the poster had in mind, but that’s my assumption (and probably somebody will eventually find this answer with such a use case in mind).It also isn’t specified how the images are stored, so I’ll make assumptions that
ImageAdapter‘s images are bundled resources of this appImageAdapter, to store some data to solve this problemSo, with that, I take a standard
ImageAdapter, and add one line of code to record the integer resource ID for each ImageView, in the ImageView’stagproperty. There’s many ways to do this, but this is the way I chose.Then, when the Hello activity has a grid item clicked, I retrieve the image’s resource id and pass it as an
Intentextra (HelloGridViewActivity.java):And finally, when the new activity (
AnotherActivity) is opened, we retrieve that intent extra, and decode it as an integer resource id, and set it as the background image with a fullscreenImageView(AnotherActivity.java):I also show above some commented out code, if for some reason you need to pass a string name of an image resource, instead of an integer resource code. The commented out code looks up the resource id for the given image name. According to the resource names used in my ImageAdapter, a sample string name to pass might be
"pic1". If you do this, of course, the calling Activity (HelloGridViewActivity) needs to encode the Intent extra as a String, not an integer.