相信大家尝试过许多方法恢复滚动位置,本人也找了许多方法,唯有这个方法好用,下面把代码贴出来
声明两个变量
private int mPosition;private int lvChildTop;
pause , resume方法
@Override public void onPause() { // TODO Auto-generated method stub super.onPause(); SharedPreferences mySharedPreferences = activity.getSharedPreferences(MY_PREFS, Activity.MODE_PRIVATE); SharedPreferences.Editor edit = mySharedPreferences.edit(); edit.putInt("mPositionChildTop", lvChildTop); edit.putInt("mPosition", mPosition); edit.commit(); } @Override public void onResume() { // TODO Auto-generated method stub super.onResume(); SharedPreferences mySharedPreferences = activity.getSharedPreferences(MY_PREFS, Activity.MODE_PRIVATE); // MY_PREFES 是声明的字符串 lvChildTop = mySharedPreferences.getInt("mPositionChildTop", 0); mPosition = mySharedPreferences.getInt("mPosition", 0); listMessage.setSelectionFromTop(mPosition, lvChildTop); // listMessage 是listview , }
private OnScrollListener lvScrollListener = new OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // TODO Auto-generated method stub // 不滚动时保存当前滚动到的位置 if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) { mPosition = listMessage.getFirstVisiblePosition(); View v = listMessage.getChildAt(0); lvChildTop = (v == null) ? 0 : v.getTop(); } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // TODO Auto-generated method stub } };