Android : Scroll position jumps on Android GridView

on Monday, October 27, 2014


I have a GridView which contains several items. By clicking an item a new detail view is created. Then by clicking back button user is returned to GridView. I want to preserve exact scroll position and I have accomplished that with following code:


Creating GridView



mArtistList = (GridView) artistsView.findViewById(R.id.gridview);
mArtistAdapter = new ArtistAdapter(mContext);
mArtistList.setAdapter(mArtistAdapter);

// Adapter gets items asynchronously
mArtistAdapter.registerDataSetObserver(new DataSetObserver() {

@Override
public void onChanged () {

// setting first selection item
mArtistList.setSelection(sActiveItem);

/*
*
* PROBLEM HERE
* Works ok, but when user touches the GridView
* scroll position jumps to position where it
* would be without this line.
*
*/
mArtistList.scrollBy(0, sActiveTop);

super.onChanged();
}
});


When user clicks an item on GridView



sActiveItem = mArtistList.getFirstVisiblePosition();

// vertical spacing (5dp to pixels)
sActiveTop = (int) (5.0f * getResources().getDisplayMetrics().density);

View firstItem = mArtistList.getChildAt(0);

if (firstItem != null) {
sActiveTop -= firstItem.getTop();
}


This works fine. Scroll position is exactly right after back button is pressed. The problem comes when user touches GridView. Scroll jumps to position where the first visible item is exactly at top of screen. How can I prevent this jump?


I don't speak english as my native language, so my explanation might be hard to understand. That's why I draw an image to indicate the problem:


enter image description here


0 comments:

Post a Comment