How to refresh a GridView?

后端 未结 9 2206
清歌不尽
清歌不尽 2020-12-01 08:01

I have a GridView which is pretty similar to the Google tutorial, except that I want to add the ImageViews on runtime (via a subactivity). The results are okay, but the layo

相关标签:
9条回答
  • 2020-12-01 08:06

    You must, first tell the adapter to notify that the data has changed and set the adapter again to the grid

    adapter.notifyDataChanged();
    grid.setAdapter(adapter);
    
    0 讨论(0)
  • 2020-12-01 08:07

    This may be helpful. I refresh a gridview of book image thumbnails after a delete is executed on an item. Using adapter.notifyDataChanged(); as mentioned above didn't work for me as it's called in my adapter.

    //this is a call that retrieves cached data.
    //your constructor can be designed and used without it.
    final Object data = getLastNonConfigurationInstance();
    

    I essentially just reload the adapter and bind it to the same view.

    //reload the adapter
    adapter = new BooksAdapter(MyBooks.this, MyBooks.this, data, show_collection );
    grid.invalidateViews();
    grid.setAdapter(adapter);
    
    0 讨论(0)
  • 2020-12-01 08:14

    @flyerz @snagnever

    Together you guys have got it. It should be:

    adapter.notifyDataChanged();
    grid.invalidateViews();
    

    This will flag the adapter that its data has changed, which will then be propagated to the grid whenever after the invalidateViews() method is called.

    Glad I found this question because I could not figure out how to add items to the grid after its been rendered.

    0 讨论(0)
  • 2020-12-01 08:18

    You are placing the GridView inside com.unimelb.pt3.ui.TransparentPanel which is 10px tall.

    • You shouldn't use px, you should use dp.
    • Change com.unimelb.pt3.ui.TransparentPanel's android:layout_height="10px" to android:layout_height="fill_parent"
    0 讨论(0)
  • 2020-12-01 08:21

    the GridView has an invalidateViews() method.

    when you call this method: "all the views to be rebuilt and redrawn." http://developer.android.com/reference/android/widget/GridView.html

    i think this is what you need:)

    0 讨论(0)
  • 2020-12-01 08:21

    In your adapter :

    class MAdapter extends BaseAdapter{
       List<Objects> mObjects;
    ...
    
     public void clearAdapter(){
            mObjects.clear();
        }
    
     public void addNewValues(List<Objects> mObjects){
            this.mObjects = mObjects;
        }
    
    ...
    
    }
    
    
    adapter.clearAdapter(); // clear old values
    adapter.addNewValues(MObjects);
    adapter.notifyDataChanged();
    
    0 讨论(0)
提交回复
热议问题