天天看點

Android清單條目跳轉,Android RrecyclerView條目跳轉到指定位置

效果圖如下:側滑點選第幾張     主界面顯示第幾章

Android清單條目跳轉,Android RrecyclerView條目跳轉到指定位置
Android清單條目跳轉,Android RrecyclerView條目跳轉到指定位置

工具類:

public class MoveToPosition {

//目标項是否在最後一個可見項之後

private static boolean mShouldScroll;

//記錄目标項位置

private static int mToPosition;

public static void MoveToPosition(LinearLayoutManager manager, RecyclerView mRecyclerView, int n) {

int firstItem = manager.findFirstVisibleItemPosition();

int lastItem = manager.findLastVisibleItemPosition();

if (n <= firstItem) {

mRecyclerView.scrollToPosition(n);

}else if (n <= lastItem) {

int top = mRecyclerView.getChildAt(n - firstItem).getTop();

mRecyclerView.scrollBy(0, top);

}else {

//            mRecyclerView.scrollToPosition(n);

manager.scrollToPositionWithOffset(n,0);

}

}

public static void smoothMoveToPosition(LinearLayoutManager manager, 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.scrollToPosition(position);

}else if (position <= lastItem) {

// 第二種可能:跳轉位置在第一個可見位置之後

int movePosition = position - firstItem;

if (movePosition >=0 && movePosition < mRecyclerView.getChildCount()) {

int top = mRecyclerView.getChildAt(movePosition).getTop();

mRecyclerView.scrollBy(0, top);

}

}else {

// 第三種可能:跳轉位置在最後可見項之後

//            mRecyclerView.smoothScrollToPosition(position);

//            mToPosition = position;

//            mShouldScroll = true;

//            mRecyclerView.scrollToPosition(position);

manager.scrollToPositionWithOffset(position,0);

mToPosition = position;

mShouldScroll =true;

}

}

}

調用方法:

titleAdapter.setOnItemClickLitener(new TitleAdapter1.OnItemClickLitener() {

@Override

public void onItemClick(View view, int position) {

drawerlayout.closeDrawers();

MoveToPosition.smoothMoveToPosition(ContentLinearLayoutManager, recyclerView, position);

}

});