【問題】
一般來說我們會使用RecyclerView的smoothScrollToPosition(int position) 方法來實現(xiàn)自動滾動袁余,但是這個方法最大的問題就是艇抠,一旦目標(biāo)position的item出現(xiàn)在屏幕中仿村,列表就不會繼續(xù)滾動闸餐,這也就造成了一種“BUG”:如果目標(biāo)position的item原本處于列表下方鲤孵,且沒有在屏幕中出現(xiàn)瘩欺,調(diào)用smoothScrollToPosition(int position)方法蜘腌,會導(dǎo)致目標(biāo)position的item滑動到屏幕下方最后一個可見位置的時候就停止滑動沫屡,在大多數(shù)需求中,這并不是我們想要的效果撮珠。
【解決方法】
這是在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, "數(shù)據(jù)" + 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>