Created
November 16, 2015 07:21
-
-
Save w4lle/8225227c99502c47cf26 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 用于记录和恢复ListView的滑动位置 | |
* Created by ONEWateR on 2015/10/16. | |
*/ | |
public class ListViewRecord { | |
private ListView mListView; | |
private int scrolledY; | |
public ListViewRecord(ListView listView) { | |
mListView = listView; | |
} | |
/** | |
* 设置listView的滑动监听 | |
*/ | |
public void initEvent() { | |
mListView.setOnScrollListener(new AbsListView.OnScrollListener() { | |
@Override | |
public void onScrollStateChanged(AbsListView view, int scrollState) { | |
// 不滚动时记录当前滚动到的位置 | |
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) { | |
record(); | |
} | |
} | |
@Override | |
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { | |
} | |
}); | |
} | |
/** | |
* 记录位置 | |
*/ | |
public void record() { | |
scrolledY = getScrollY(); | |
} | |
/** | |
* 获取ListView的ScrollY | |
* @return | |
*/ | |
public int getScrollY() { | |
View c = mListView.getChildAt(0); | |
if (c == null) { | |
return 0; | |
} | |
int firstVisiblePosition = mListView.getFirstVisiblePosition(); | |
int top = c.getTop(); | |
return -top + firstVisiblePosition * c.getHeight() ; | |
} | |
/** | |
* 恢复位置 | |
*/ | |
public void restore() { | |
mListView.post(new Runnable() { | |
@Override | |
public void run() { | |
mListView.smoothScrollBy(scrolledY, 0); | |
} | |
}); | |
} | |
} | |
使用方法: | |
初始化 | |
ListViewRecord record = new ListViewRecord(listView); | |
record.initEvent(); | |
恢复 | |
record.restore(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment