我编写了一个处理程序来维护回收视图的自动滚动。它工作正常。但是当回收站视图中只有一个项目时我面临的问题。我的应用程序崩溃了,当我检查 logcat 时,我收到类似 java.lang.IllegalArgumentException: Invalid target position 的错误。
这是我的自定义 LinearLayoutManager 类
public class CustomLinearLayoutManager extends LinearLayoutManager {
public CustomLinearLayoutManager (Context context) {
super(context);
}
public CustomLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
public CustomLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
final LinearSmoothScroller linearSmoothScroller =
new LinearSmoothScroller(recyclerView.getContext()) {
private static final float MILLISECONDS_PER_INCH = 100f;
@Override
public PointF computeScrollVectorForPosition(int targetPosition) {
return CustomLinearLayoutManager.this
.computeScrollVectorForPosition(targetPosition);
}
@Override
protected float calculateSpeedPerPixel
(DisplayMetrics displayMetrics) {
return MILLISECONDS_PER_INCH / displayMetrics.densityDpi;
}
};
linearSmoothScroller.setTargetPosition(position);
startSmoothScroll(linearSmoothScroller);
}
}
Run Code Online (Sandbox Code Playgroud)
这是这一行的一个获取错误:
startSmoothScroll(linearSmoothScroller);
Run Code Online (Sandbox Code Playgroud)
错误是 - CustomLinearLayoutManager.smoothScrollToPosition java.lang.IllegalArgumentException:目标位置无效
这是家庭片段的代码
recyclerViewHeaderSlider.setLayoutManager(new CustomLinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
headerSliderAdapter.setOnClick(this);
recyclerViewHeaderSlider.setAdapter(headerSliderAdapter);
final int speedScroll = 6000;
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
int count = 0;
boolean flag = true;
@Override
public void run() {
if (count < headerSliderAdapter.getItemCount()) {
if (count == headerSliderAdapter.getItemCount() - 1) {
flag = false;
} else if (count == 0) {
flag = true;
}
if (flag) count++;
else count--;
recyclerViewHeaderSlider.smoothScrollToPosition(count);
handler.postDelayed(this, speedScroll);
}
}
};
handler.postDelayed(runnable, speedScroll);
Run Code Online (Sandbox Code Playgroud)
这是这一行的一个获取错误:
recyclerViewHeaderSlider.smoothScrollToPosition(count);
Run Code Online (Sandbox Code Playgroud)
错误是 - java.lang.IllegalArgumentException:目标位置无效
该错误是由负索引 (-1) 引起的。
看看这段代码:
if (count == headerSliderAdapter.getItemCount() - 1) {
flag = false;
} else if (count == 0) {
flag = true;
}
Run Code Online (Sandbox Code Playgroud)
如果您的项目数为 1,则第一个if将是truewhen count == 0。1 - 1 = 0 所以flag = false。
然后,当你到达第二个时if:
if (flag) count++;
else count--;
Run Code Online (Sandbox Code Playgroud)
flag是false这样您的代码将执行count--但count已经为 0,因此您得到count == -1.
然后您尝试滚动到负位置,这是不允许的。
| 归档时间: |
|
| 查看次数: |
2068 次 |
| 最近记录: |