相信大家嘗試過許多方法恢復滾動位置,本人也找了許多方法,唯有這個方法好用,下面把代碼貼出來
聲明兩個變量
[java]
private int mPosition;
private int lvChildTop;
pause , resume方法
[java]
@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 ,
}
listview 的監聽事件
[java
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
}
};