欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

RecyclerView滑動到指定Position的方法

 更新時(shí)間:2017年04月06日 17:16:34   作者:陸羽_  
這篇文章主要為大家詳細(xì)介紹了RecyclerView滑動到指定Position的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

Question

最近在寫 SideBar 的時(shí)候遇到一個(gè)問題,當(dāng)執(zhí)行 Recyclerview 的 smoothScrollToPosition(position) 的時(shí)候,Recyclerview 看上去并沒有滾動到指定位置。

Analysis

當(dāng)然,這并不是方法的bug,而是 smoothScrollToPosition(position) 的執(zhí)行效果有三種情況,需要區(qū)分。

·目標(biāo)position在第一個(gè)可見項(xiàng)之前 。

這種情況調(diào)用smoothScrollToPosition能夠平滑的滾動到指定位置,并且置頂。

·目標(biāo)position在第一個(gè)可見項(xiàng)之后,最后一個(gè)可見項(xiàng)之前。

這種情況下,調(diào)用smoothScrollToPosition不會有任何效果···

·目標(biāo)position在最后一個(gè)可見項(xiàng)之后。

這種情況調(diào)用smoothScrollToPosition會把目標(biāo)項(xiàng)滑動到屏幕最下方···

Solution

鑒于這三種情況,我想大多數(shù)情況下都無法滿足我們的滑動要求。為了實(shí)現(xiàn) Recyclerview 把指定 item 滑動到屏幕頂端的需求,我們需要對上面三種情況分別處理。

 /** 目標(biāo)項(xiàng)是否在最后一個(gè)可見項(xiàng)之后*/
 private boolean mShouldScroll;
 /** 記錄目標(biāo)項(xiàng)位置*/
 private int mToPosition;

 /**
 * 滑動到指定位置
 * @param mRecyclerView
 * @param position
 */
 private void smoothMoveToPosition(RecyclerView mRecyclerView, final int position) {
 // 第一個(gè)可見位置
 int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0));
 // 最后一個(gè)可見位置
 int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1));

 if (position < firstItem) {
 // 如果跳轉(zhuǎn)位置在第一個(gè)可見位置之前,就smoothScrollToPosition可以直接跳轉(zhuǎn)
 mRecyclerView.smoothScrollToPosition(position);
 } else if (position <= lastItem) {
 // 跳轉(zhuǎn)位置在第一個(gè)可見項(xiàng)之后,最后一個(gè)可見項(xiàng)之前
 // smoothScrollToPosition根本不會動,此時(shí)調(diào)用smoothScrollBy來滑動到指定位置
 int movePosition = position - firstItem;
 if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) {
 int top = mRecyclerView.getChildAt(movePosition).getTop();
 mRecyclerView.smoothScrollBy(0, top);
 }
 }else {
 // 如果要跳轉(zhuǎn)的位置在最后可見項(xiàng)之后,則先調(diào)用smoothScrollToPosition將要跳轉(zhuǎn)的位置滾動到可見位置
 // 再通過onScrollStateChanged控制再次調(diào)用smoothMoveToPosition,執(zhí)行上一個(gè)判斷中的方法
 mRecyclerView.smoothScrollToPosition(position);
 mToPosition = position;
 mShouldScroll = true;
 }
 }

再通過onScrollStateChanged控制再次調(diào)用smoothMoveToPosition

 mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
 @Override
 public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
 super.onScrollStateChanged(recyclerView, newState);
 if (mShouldScroll){
  mShouldScroll = false;
  smoothMoveToPosition(mRecyclerView,mToPosition);
 }
 }
 });
 }

目前這個(gè)解決方法有兩個(gè)已知的問題

1、當(dāng)目標(biāo)項(xiàng)在最后一個(gè)可見項(xiàng)之后的時(shí)候,由于我們先執(zhí)行smoothScrollToPosition方法,然后在OnScrollListener中執(zhí)行smoothMoveToPosition方法,在滑動的時(shí)候不夠連貫。
2、在手動滑動的時(shí)候執(zhí)行該方法,會有極小的概率滑動的位置出現(xiàn)偏差。
如果你有更好解決辦法,希望不吝指教。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論