RecyclerView滑動到指定位置,並置頂


一般我們用 mRecycleview.smoothScrollToPosition(0)滑動到頂部,具有滾動效果,但是如果我們想滾動到任意指定位置,那么smoothScrollToPosition()就不能保證所指定item位於屏幕頂部,那么一下提供下我解決的方法:

1.第一種方法

此方法能實現指定位置位於屏幕頂部,但是不具有平滑滾動視覺效果:

 if (position != -1) { mRecycleview.scrollToPosition(position); LinearLayoutManager mLayoutManager = (LinearLayoutManager) mRecycleview.getLayoutManager();這里的LinearLayoutManager對象只能是動態獲取,不能用全局的。
 mLayoutManager.scrollToPositionWithOffset(position, 0); }

2.第二種方法

此方法能實現指定位置位於屏幕頂部,具有平滑滾動視覺效果:

首先獲取第一個可見位置和最后一個可見位置,分三種情況:

1.如果如果跳轉位置在第一個可見位置之前,就smoothScrollToPosition()可以直接跳轉; 
2.如果跳轉位置在第一個可見項之后,最后一個可見項之前smoothScrollToPosition()不會滾動,此時調用smoothScrollBy來滑動到指定位置; 
3.如果要跳轉的位置在最后可見項之后,則先調用smoothScrollToPosition()將要跳轉的位置滾動到可見位置,在addOnScrollListener()里通過onScrollStateChanged控制,調用smoothMoveToPosition,再次執行判斷;

 //目標項是否在最后一個可見項之后 private boolean mShouldScroll; //記錄目標項位置 private int mToPosition; /** * 滑動到指定位置 */ private void smoothMoveToPosition(RecyclerView mRecyclerView, final int position) { // 第一個可見位置 int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0)); // 最后一個可見位置 int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1)); if (position < firstItem) { // 第一種可能:跳轉位置在第一個可見位置之前 mRecyclerView.smoothScrollToPosition(position); } else if (position <= lastItem) { // 第二種可能:跳轉位置在第一個可見位置之后 int movePosition = position - firstItem; if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) { int top = mRecyclerView.getChildAt(movePosition).getTop(); mRecyclerView.smoothScrollBy(0, top); } } else { // 第三種可能:跳轉位置在最后可見項之后 mRecyclerView.smoothScrollToPosition(position); mToPosition = position; mShouldScroll = true; } }
 mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (mShouldScroll) { mShouldScroll = false; smoothMoveToPosition(irc, mToPosition); } } });
if (position != -1) { smoothMoveToPosition(irc,position); }else { smoothMoveToPosition(irc,position+1); }


改文章出自:https://blog.csdn.net/shanshan_1117/article/details/78780137
特此感謝!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM