ArrayIndexOutOfBoundsException when populating RecyclerView

前端 未结 3 2024
自闭症患者
自闭症患者 2021-01-06 23:02

I am getting an error every so often when I try to populate my RecyclerView but the error seems to happening internally in the StaggeredGridLayoutManager.

3条回答
  •  我在风中等你
    2021-01-06 23:50

    This crash happen when you try to notifyDataSetChanged/notifyItemRemoved/Added/change while RecyclerView isComputingLayout

    This case may happen if you have some custom logic to change adapter contents in response to a View callback

    In these cases, you should just postpone the change using a Handler

    DON'T notify change until RecyclerView.isComputingLayout() return false.

     /**
         * Returns whether RecyclerView is currently computing a layout.
         * 

    * If this method returns true, it means that RecyclerView is in a lockdown state and any * attempt to update adapter contents will result in an exception because adapter contents * cannot be changed while RecyclerView is trying to compute the layout. *

    * It is very unlikely that your code will be running during this state as it is * called by the framework when a layout traversal happens or RecyclerView starts to scroll * in response to system events (touch, accessibility etc). *

    * This case may happen if you have some custom logic to change adapter contents in * response to a View callback (e.g. focus change callback) which might be triggered during a * layout calculation. In these cases, you should just postpone the change using a Handler or a * similar mechanism. * * @return true if RecyclerView is currently computing a layout, false * otherwise */ public boolean isComputingLayout() { return mLayoutOrScrollCounter > 0; }

提交回复
热议问题