RecyclerView smoothScroll位于中心位置.安卓
作者:互联网
我正在为RecyclerView使用水平布局管理器.
我需要以下一种方式制作RecyclerView:当点击某个项目时 – 将smoothScrool放到该位置并将该项目放在RecyclerView的中心(如果可能的话,例如20中的10项).
所以,我对smoothScrollToPosition()没有问题,但是如何把项目放在RecyclerView的中心?
谢谢!
解决方法:
是的,这是可能的.
通过实现RecyclerView.SmoothScroller的方法onTargetFound(View,State,Action).
/**
* Called when the target position is laid out. This is the last callback SmoothScroller
* will receive and it should update the provided {@link Action} to define the scroll
* details towards the target view.
* @param targetView The view element which render the target position.
* @param state Transient state of RecyclerView
* @param action Action instance that you should update to define final scroll action
* towards the targetView
*/
abstract protected void onTargetFound(View targetView, State state, Action action);
特别是在LinearLayoutManager中使用LinearSmoothScroller:
public class CenterLayoutManager extends LinearLayoutManager {
public CenterLayoutManager(Context context) {
super(context);
}
public CenterLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
public CenterLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
RecyclerView.SmoothScroller smoothScroller = new CenterSmoothScroller(recyclerView.getContext());
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
}
private static class CenterSmoothScroller extends LinearSmoothScroller {
CenterSmoothScroller(Context context) {
super(context);
}
@Override
public int calculateDtToFit(int viewStart, int viewEnd, int boxStart, int boxEnd, int snapPreference) {
return (boxStart + (boxEnd - boxStart) / 2) - (viewStart + (viewEnd - viewStart) / 2);
}
}
}
标签:android,android-recyclerview,linearlayoutmanager 来源: https://codeday.me/bug/20190930/1835102.html