发生 java.lang.IllegalArgumentException

我编写了一个处理程序来维护回收器视图的自动滚动。工作正常。但是当回收器视图中只有一项时我遇到的问题。我的应用程序崩溃了,当我检查 logcat 时,我收到类似 java.lang.IllegalArgumentException: 无效目标位置的错误。


这是我的自定义 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);

    }

}

这是该行的一个获取错误:


startSmoothScroll(linearSmoothScroller);

错误是 - CustomLinearLayoutManager.smoothScrollToPosition java.lang.IllegalArgumentException:目标位置无效


这是该行的一个获取错误:


recyclerViewHeaderSlider.smoothScrollToPosition(count);

错误是 - java.lang.IllegalArgumentException:目标位置无效


BIG阳
浏览 101回答 3
3回答

皈依舞

该错误是由于负索引 (-1) 造成的。看这段代码:if (count == headerSliderAdapter.getItemCount() - 1) {    flag = false;} else if (count == 0) {    flag = true;}如果您的项目数为 1,那么第一个项目if将true在 时出现count == 0。1 - 1 = 0 所以flag = false。然后,当你到达第二个时if:if (flag) count++;else count--;flag是false这样你的代码将执行count--但count已经是 0,因此你得到count == -1.然后你尝试滚动到负位置,这是不允许的。

白板的微信

不要使用非线程安全的延迟后方法。    private fun scrollToLastItem(view: View) {      //pos.coerceAtLeast(0) // Use this        view.recycler_view.smoothScrollToPosition(pos.coerceAtLeast(0))    }RCA:在 ScrollLayoutManager startSmoothPendingScroll 方法崩溃之前,当前位置为 -1。

鸿蒙传说

它也可以(在最后一个位置的情况下):private fun scrollToLastItem(view: View) {    adapter.itemCount.takeIf { it > 0 }?.let {        view.recycler_view.smoothScrollToPosition(it - 1)    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java