在项目中,想使RecyclerView慢慢的平缓滑动指定位置,于是使用:
RecyclerView.smoothScrollToPosition(int);
发现效果并不理想,滑动过程很突兀,很快就滑动到了指定位置,并没有像函数名那样smooth(流畅的,平滑的),也就是说smoothScrollToPosition没有滑动效果?
这里接不说底层原理了,网上一大把!
解决办法 重写LinearLayoutManager自定义滑动速度:
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
/**
* Created by tyl
* 2018/12/19/019
* Describe:解决 RecyclerView调用smoothScrollToPosition时没有起到平滑的作用
* 设置LinerLayoutManager:recyclerview.setLayoutManager(new SmoothScrollLayoutManager(this));
*recyclerview.smoothScrollToPosition(i);
*/
public class SmoothScrollLayoutManager extends LinearLayoutManager {
public SmoothScrollLayoutManager(Context context) {
super(context);
}
@Override
public void smoothScrollToPosition(RecyclerView recyclerView,
RecyclerView.State state, final int position) {
LinearSmoothScroller smoothScroller =
new LinearSmoothScroller(recyclerView.getContext()) {
// 返回:滑过1px时经历的时间(ms)。
@Override
protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
return 150f / displayMetrics.densityDpi;
}
};
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
}
}
网友评论