gpt4 book ai didi

java - Android smoothScrollToPosition 无法正常工作

转载 作者:行者123 更新时间:2023-12-02 01:37:56 27 4
gpt4 key购买 nike

我使用此函数滚动到水平回收器 View 内的选定位置。问题是,如果我滚动回收器然后单击某个项目,它不会转到 View 的中心。相反,如果我不滚动回收器,它就会起作用。当我单击某个项目时,我正在使用此方法。该位置是适配器位置。

override fun scrollToSelected(position: Int, isLeftScroll: Boolean) {
if(!isLeftScroll || position == 0) contactRV.layoutManager?.smoothScrollToPosition(contactRV, RecyclerView.State(), position +1)
else contactRV.layoutManager?.smoothScrollToPosition(contactRV, RecyclerView.State(), position-1)

我应该怎么做才能解决这个问题?

最佳答案

您将通过实现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);

特别是在 LinearLayoutManagerLinearSmoothScroller 中:

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);
}
}
}

关于java - Android smoothScrollToPosition 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54940965/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com