Reload GridView without scrolling - Android

Posted by Editor | 9/27/2013 04:40:00 pm | 0 comments »

How to prevent GridView from scrolling while reloading data?

Common mistake developers make is they create new Adapters and set it to the GridView to reload or refresh the content.

This will result in the grid scrolling towards the top which in turn makes your App less user friendly.

You can prevent GridView from scrolling up while refreshing data by re-using the Adapter created and just reloading the data.

For this, add a method say refillItems() in your Adapter implementation class as given below:

public void refillItems(List<HashMap<String,String>> items) {
    _items.clear();
    _items.addAll(items);
    notifyDataSetChanged();
}

Now call refillItems() from your Activity class whenever new set of data is available(or at fixed intervals):

GridView gView = (GridView) findViewById(R.id.grid);
if (gView.getAdapter() == null) {
    MyAdapter myAdapter = new MyAAdapter(MyActivity.this, items);
    gView.setAdapter(myAdapter);
} else {
    MyAdapter myAdapter = ((MyAdapter)gView.getAdapter());
    myAdapter.refillItems(items);
}

This will make sure the grid is not scrolled back to the top.



Tags: | | | |

0 comments

Post a Comment

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to our feed and get articles like this delivered automatically to your feed reader? Like our Facebook Page.

Recommended products for you

 
texient.com