RecycleView聯(lián)動切換列表

ezgif-5-3fd86986ba4b.gif

點(diǎn)擊左邊的type標(biāo)簽可以切換右邊對應(yīng)的列表數(shù)據(jù)的位置,滑動右邊的列表可以自動匹配到左邊的type標(biāo)簽。具體實(shí)現(xiàn)可以用兩個Recyleview來實(shí)現(xiàn),利用smoothScrolltoPosition()方法。

/**
* Starts a smooth scroll to an adapter position.
* <p>
* To support smooth scrolling, you must override
* {@link LayoutManager#smoothScrollToPosition(RecyclerView, State, int)} and create a
* {@link SmoothScroller}.
* <p>
* {@link LayoutManager} is responsible for creating the actual scroll action. If you want to
* provide a custom smooth scroll logic, override
* {@link LayoutManager#smoothScrollToPosition(RecyclerView, State, int)} in your
* LayoutManager.
*
* @param position The adapter position to scroll to
* @see LayoutManager#smoothScrollToPosition(RecyclerView, State, int)
*/
public void smoothScrollToPosition(int position) {
if (mLayoutFrozen) {
return;
}
if (mLayout == null) {
Log.e(TAG, "Cannot smooth scroll without a LayoutManager set. "
+ "Call setLayoutManager with a non-null argument.");
return;
}
mLayout.smoothScrollToPosition(this, mState, position);
}

由于recycleview緩存的機(jī)制,這個方法有時(shí)達(dá)不到想要的效果所以要再進(jìn)行判斷結(jié)合smoothScrollBy方法來實(shí)現(xiàn)效果

 int first = mGridLayoutManager.findFirstVisibleItemPosition();
 int last = mGridLayoutManager.findLastVisibleItemPosition();
 int pos = mItemCountList2.get(position);
 if (pos < first) {
    LogUtils.LogE("0");
    mRvRight.smoothScrollToPosition(pos);

1.當(dāng)你想要切換的位置小于右邊列表第一個可見的條目位置,這個方法可以達(dá)到的效果

} else if (pos >= first && pos < last) {
            int top = mRvRight.getChildAt(pos - first).getTop();
            LogUtils.LogE("top = " + top);
            mRvRight.smoothScrollBy(0, top);

2.當(dāng)你想要切換的位置大于等于右邊第一個可見條目的位置并且小于最后一個可見條目的時(shí)候利用smoothScrollBy方法實(shí)現(xiàn)

  else if (pos >= last) {
             LogUtils.LogE("2");
             mRvRight.smoothScrollToPosition(pos);

3.當(dāng)切換的位置大于等于右邊最后一個可見條目smoothScrollToPosition方法只能把該條目置底不能置頂,所以在滾動結(jié)束后再利用
smoothScrollBy方法強(qiáng)制移動到頂部

if (newState == RecyclerView.SCROLL_STATE_IDLE) {
    int last = mGridLayoutManager.findLastVisibleItemPosition();
    if (mDatasBeanList.get(last).getLabel() != null && mDatasBeanList.get(last).getLabel().equals(mTag)) {
       mRvRight.smoothScrollBy(0, mHeight - mItemHeight);
    }
 }

代碼已上傳https://github.com/digtal/recycleview-study
有問題留言溝通哈!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容