RecyclerView 点击定位功能
用RecyclerView提供的控制移动的2个方法
- scrollToPosition(int)
- scrollBy(int x,int y)
这个方法是自己去控制移动的距离,单位应该是像素。
使用scrollToPosition时,你会发现它时准时不准,有时候会把你要移动的位置置顶,有时候就胡乱定位。
思路是:先用scrollToPosition,将要置顶的位置移动显示出来,然后通过RecyclerView的onScrolled 方法来算出还剩下多少距离,再用scrollBy 移动
关键代码
private LinearLayoutManager mLinearLayoutManager;
private boolean move = false;
private int mIndex = 0;
/**
* 点击 站点定位
*
* @param n
*/
private void moveToPosition(int n) {
mIndex = n;
//先从RecyclerView的LayoutManager中获取第一项和最后一项的Position
int firstItem = mLinearLayoutManager.findFirstVisibleItemPosition();
int lastItem = mLinearLayoutManager.findLastVisibleItemPosition();
//然后区分情况
if (n <= firstItem) {
//当要置顶的项在当前显示的第一个项的前面时
rv_station.scrollToPosition(n);
} else if (n <= lastItem) {
//当要置顶的项已经在屏幕上显示时
int top = rv_station.getChildAt(n - firstItem).getTop();
rv_station.scrollBy(0, top);
} else {
//当要置顶的项在当前显示的最后一项的后面时
rv_station.scrollToPosition(n);
//这里这个变量是用在RecyclerView滚动监听里面的
move = true;
}
}
RecyclerView滚动监听
rv_station.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
//做出最后的判断滚动
if (move) {
move = false;
//获取要置顶的项在当前屏幕的位置,mIndex是记录的要置顶项在RecyclerView中的位置
int n = mIndex - mLinearLayoutManager.findFirstVisibleItemPosition();
if (0 <= n && n < rv_station.getChildCount()) {
//获取要置顶的项顶部离RecyclerView顶部的距离
int top = rv_station.getChildAt(n).getTop();
//最后移动
rv_station.scrollBy(0, top);
}
}
}
});
这样就可以确保万无一失的移动到你想要的位置了!
上面这种方法是直接把你想要定位的位置置顶,没有滑动的过程。
下面是带滑动的置顶:
private void smoothMoveToPosition(int n) {
int firstItem = mLinearLayoutManager.findFirstVisibleItemPosition();
int lastItem = mLinearLayoutManager.findLastVisibleItemPosition();
if (n <= firstItem ){
mRecyclerView.smoothScrollToPosition(n);
}else if ( n <= lastItem ){
int top = mRecyclerView.getChildAt(n - firstItem).getTop();
mRecyclerView.smoothScrollBy(0, top);
}else{
mRecyclerView.smoothScrollToPosition(n);
move = true;
}
}
rv_station.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (move && newState == RecyclerView.SCROLL_STATE_IDLE){
move = false;
int n = mIndex - mLinearLayoutManager.findFirstVisibleItemPosition();
if ( 0 <= n && n < mRecyclerView.getChildCount()){
int top = mRecyclerView.getChildAt(n).getTop();
mRecyclerView.smoothScrollBy(0, top);
}
}
}
});
两种方式择一即可!