【问题】
一般来说我们会使用RecyclerView的smoothScrollToPosition(int position) 方法来实现自动滚动,但是这个方法最大的问题就是,一旦目标position的item出现在屏幕中,列表就不会继续滚动,这也就造成了一种“BUG”:如果目标position的item原本处于列表下方,且没有在屏幕中出现,调用smoothScrollToPosition(int position)方法,会导致目标position的item滑动到屏幕下方最后一个可见位置的时候就停止滑动,在大多数需求中,这并不是我们想要的效果。
【解决方法】
这是在StackOverflow上找到的解决办法:
RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(this){
@Override
protected int getVerticalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_START;
}
};
LinearLayoutManager mManager = new LinearLayoutManager(context);
smoothScroller.setTargetPosition(position);
mManager.startSmoothScroll(smoothScroller);
【核心代码】
/**
* @Author Lee
* @Time 2018/3/8
* @Theme 列表自动滑动到指定的position
*/
public class ScrollToTopActivity extends AppCompatActivity {
private RecyclerView mRv;
private TestDataAdapter mAdapter;
private ArrayList<String> datas = new ArrayList<>();
private ImageView mIvTop;
private RecyclerView.SmoothScroller smoothScroller;
private LinearLayoutManager mManager;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activit_scroll_to_top);
initView();
}
private void initView() {
mRv = findViewById(R.id.recylerview);
mIvTop = findViewById(R.id.iv_top);
for (int i = 0; i < 100; i++) {
datas.add(i, "数据" + i);
}
mAdapter = new TestDataAdapter(this, datas);
mManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
mRv.setLayoutManager(mManager);
mRv.setAdapter(mAdapter);
smoothScroller = new LinearSmoothScroller(this) {
@Override
protected int getVerticalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_START;
}
};
LinearLayoutManager mManager = new LinearLayoutManager(this);
mIvTop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Toast.makeText(ScrollToTopActivity.this, "回到顶部", Toast.LENGTH_SHORT).show();
// mRv.smoothScrollToPosition(10);
smoothScroller.setTargetPosition(10);
mManager.startSmoothScroll(smoothScroller);
}
});
}
}
【xml 布局】
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/recylerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<RelativeLayout
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/iv_top"
android:layout_width="50dp"
android:layout_marginRight="@dimen/margin_10dp"
android:layout_marginBottom="@dimen/margin_10dp"
android:layout_height="50dp"
android:src="@mipmap/icon_guide_dot"
android:tooltipText="h"
/>
</RelativeLayout>
</RelativeLayout>