Android recyclerview的滑动到指定的item
1.滑动到指定位置的方法要写在数据真正加载完成以后,而不是加载数据方法的后面。
2.指定的位置是否可见。
快速定位
public static void MoveToPosition(int n) {
manager.scrollToPosition(n);
}
缓慢定位(借鉴网络上整理)
/**
* 缓慢滑动
*
* 当指定位置位于第一个可见位置之上时,可以滚动,利用smoothScrollToPosition实现
* 当指定位置位于可视位置之间时,得到距离顶部的距离,然后smoothScrollBy向上滚动固定的距离
* 当指定的位置位于最后一个可见位置之下时,可以滚动,利用利用smoothScrollToPosition实现实现
*/
public void moveToPosition(int position) {
int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0));
int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1));
if (position < firstItem||position>lastItem) {
mRecyclerView.smoothScrollToPosition(position);
} else {
int movePosition = position - firstItem;
int top = mRecyclerView.getChildAt(movePosition).getTop();
mRecyclerView.smoothScrollBy(0, top);
}
}
另一种获得可见位置的方法
public void moveToPosition(RecyclerView recyclerView, int position) {
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
//因为只有LinearLayoutManager 才有获得可见位置的方法
if (layoutManager instanceof LinearLayoutManager) {
LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
int firstItem = linearLayoutManager.findFirstVisibleItemPosition();
int lastItem = linearLayoutManager.findLastVisibleItemPosition();
if (position < firstItem || position > lastItem) {
mRecyclerView.smoothScrollToPosition(position);
} else {
int movePosition = position - firstItem;
int top = mRecyclerView.getChildAt(movePosition).getTop();
mRecyclerView.smoothScrollBy(0, top);
}
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 【.NET】调用本地 Deepseek 模型
2015-05-06 SVN使用教程之——分支、合并