点击左边的type标签可以切换右边对应的列表数据的位置,滑动右边的列表可以自动匹配到左边的type标签。具体实现可以用两个Recyleview来实现,利用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缓存的机制,这个方法有时达不到想要的效果所以要再进行判断结合smoothScrollBy方法来实现效果
int first = mGridLayoutManager.findFirstVisibleItemPosition();
int last = mGridLayoutManager.findLastVisibleItemPosition();
int pos = mItemCountList2.get(position);
if (pos < first) {
LogUtils.LogE("0");
mRvRight.smoothScrollToPosition(pos);
1.当你想要切换的位置小于右边列表第一个可见的条目位置,这个方法可以达到的效果
} else if (pos >= first && pos < last) {
int top = mRvRight.getChildAt(pos - first).getTop();
LogUtils.LogE("top = " + top);
mRvRight.smoothScrollBy(0, top);
2.当你想要切换的位置大于等于右边第一个可见条目的位置并且小于最后一个可见条目的时候利用smoothScrollBy方法实现
else if (pos >= last) {
LogUtils.LogE("2");
mRvRight.smoothScrollToPosition(pos);
3.当切换的位置大于等于右边最后一个可见条目smoothScrollToPosition方法只能把该条目置底不能置顶,所以在滚动结束后再利用
smoothScrollBy方法强制移动到顶部
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
有问题留言沟通哈!
网友评论