Search code examples
javaandroidandroid-gridviewandroid-broadcast

Efficiently update GridView child Views


I have a GridView containing ImageViews, I would like to refresh the Views if an image is successfully downloaded and converted into a Bitmap object. The GridView's adapter has a getView method that can set a default image or decode to Bitmap the downloaded image if it exists.

To refresh the GridView I can use the myGridView.getAdapter().notifyDataSetChanged() method, so I created a BroadcastReceiver able to detect if a successfully downloaded file is one of the images I need and eventually send a Listener event to the activity containing the GridView to refresh it. Since the GridView adapter can even contain thousands of elements, I would like to execute launch notifyDataSetChanged only if the View for that specific file is visible.

I thought to do something like this:

for(int i=0;i<myGridView.getChildCount();i++){
    if(myGridView.getChildAt(i).isTheOneINeed) { //notifyDataSetChanged(); break; }
}

But I'm a bit concerned: what if the user scrolls the GridView and the childView becomes null or it's replaced by one of the next items in the Adapter? Is there a safer way to do this?


Solution

  • My personal opinion is you should not play with ListView/GridView children (unless you REALLY need to). If your data has changed you should call notifyDataSetChanged(). ListView/GridView will redraw just a few items (those that are visible), even if you have thousands of them.

    To optimize your code and call notifyDataSetChanged() only when the item is visible, you can get the first and last visible positions by calling getFirstVisiblePosition() and getLastVisiblePosition()