Android GridView - Update View by Position

I have a GridView using a custom adapter (myAdapter extends BaseAdapter), where each element in the grid contains an ImageButton. getView () is working fine.

However, from other places in my code, how can I update the image (setImageResource) for one specific element in the grid depending on its position in the GridView?

So far, I have added this to my adapter class:

public void changeImage() { Log.d(TAG, "Image change"); this.ImageButton.setImageResource(R.drawable.newImage); } 

And I would like to write something like this: mygridview.getItemIdAtPosition(20).changeImage(); (not compiled).

+4
source share
3 answers

If you want to update the image for one specific element in the grid, what you can do is ... have onClickListener for all the images in the grid.

Now, when u clicks on any image, find the position of the image and change the original cheers resource for that particular image.

Example:

When adding an image: imageView.setOnClickListener (imageListener);

And the listener will look like dis:

 private OnClickListener imageListener = new OnClickListener() { public void onClick(View v) { int id = v.getId(); ImageView imgView = imageArray.get(id); imgView .setBackgroundResource(R.drawable.newImage); }; 

I hope you will like it.

+3
source

In the case of images in the GridView, I did this and it also works:

 gridview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View imgView, int position, long id) { ImageView imageView = (ImageView) imgView; imageView.setImageResource(R.drawable.newImage); } }); } 
+3
source

This is also my last problem. Here is my solution. I use the data Model and adapter for my RecyclerView First, register your new data in your model

  DataModel detail = new DataModel(id, name, sat, image); 

use set to replace the old value with the new

  mData.set(index, detail); 

finally upgrade your adapter

  if(adapter!=null) adapter.notifyItemChanged(index); 
0
source

Source: https://habr.com/ru/post/1300551/


All Articles