m_RecyclerListViewContent.addOnScrollListener(new MyScrollListener()); // 滑动监听
// 恢复记忆位置
if (CMineManagerModel.getInstance().getMineContentPosition() != null) {
resetListPosition();
}
/**
* 滑动监听
*/
public class MyScrollListener extends RecyclerView.OnScrollListener {
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
boolean hasStarted = newState == RecyclerView.SCROLL_STATE_DRAGGING; // 此时,RecyclerView滚动开始
boolean hasEnded = newState == RecyclerView.SCROLL_STATE_IDLE; // 此时,RecyclerView滚动结束
if (hasEnded && m_LayoutManager != null) {
View topView = m_LayoutManager.getChildAt(0);
if (topView == null) {
return;
}
m_MinePagePositionBean.setLastOffset(topView.getTop());
m_MinePagePositionBean.setLastPosition(m_LayoutManager.getPosition(topView));
m_MineContentPosition.put(m_ServiceName, m_MinePagePositionBean);
Log.d(TAG, "MyScrollListener lastOffset : " + m_MinePagePositionBean.getLastOffset() + ", lastPosition : " + m_MinePagePositionBean.getLastPosition() + " m_ServiceName : " + m_ServiceName);
CMineManagerModel.getInstance().setMineContentPosition(m_MineContentPosition);
}
}
}
private static class PositionRunnable implements Runnable {
private final int lastPosition;
private final int lastOffset;
private WeakReference<CMineContentFragment> cMineContentFragmentWeakReference;
public PositionRunnable(CMineContentFragment cMineContentFragment, int lastPosition, int lastOffset){
cMineContentFragmentWeakReference = new WeakReference<>(cMineContentFragment);
this.lastPosition = lastPosition;
this.lastOffset = lastOffset;
}
@Override
public void run() {
CMineContentFragment cMineContentFragment = cMineContentFragmentWeakReference.get();
if(cMineContentFragment != null) {
((LinearLayoutManager) cMineContentFragment.m_LayoutManager).scrollToPositionWithOffset(lastPosition, lastOffset);
}
}
}
private void resetListPosition() {
Log.d(TAG, "resetListPosition");
Log.d(TAG, "resetListPosition lastPosition to" + m_MineContentPosition.keySet());
if (m_MineContentPosition != null) {
if (m_MineContentPosition.get(m_ServiceName) != null) {
int lastOffset = m_MineContentPosition.get(m_ServiceName).getLastOffset();
int lastPosition = m_MineContentPosition.get(m_ServiceName).getLastPosition();
if (m_LayoutManager != null) {
Log.d(TAG, "resetListPosition lastPosition to" + lastPosition);
Log.d(TAG, "resetListPosition lastOffset to" + lastOffset);
PositionRunnable runnable = new PositionRunnable(this, lastPosition, lastOffset);
m_RecyclerListViewContent.post(runnable);
}
} else {
Log.d(TAG, "resetListPosition position.get(m_ServiceName) is null");
}
} else {
Log.d(TAG, "resetListPosition position is null");
}
}
Andoird --- RecycleView 恢复上次滚动到的位置
于 2023-06-20 19:48:55 首次发布