Problems专题:RecyclerView
0x01 Called attach on a child which is not detached
1 | java.lang.IllegalArgumentException: Called attach on a child which is not detached: BaseViewHolder{2b241e1 position=12 id=-1, oldPos=-1, pLpos:-1} androidx.recyclerview.widget.RecyclerView{afecb06 VFED..... ......ID 0,0-1080,2055 #7f09236e app:id/recycler_view_xxx}, adapter:com.xxxx.adapter.XxxAdapter@cfc75c7, layout:androidx.recyclerview.widget.LinearLayoutManager@24af7f4, context:com.xxxx.XxxActivity@1ed75e2 |
问题分析
对同一个 position 位置同时进行notifyItemRemoved(position) 和 notifyItemInserted(position) 操作导致。
解决方案
避免同时对同一个位置先 notifyItemRemoved 再 notifyItemInserted,使用 notifyItemChanged。
1 | adapter?.notifyItemChanged(position) |
0x02 RecyclerView设置最大高度、宽度
当RecyclerView属性设置为wrap_content+maxHeight时,maxHeight没有效果。
问题分析
当RecyclerView的LayoutManager#isAutoMeasureEnabled()返回true时,RecyclerView高度取决于children view的布局高度,并非取决于RecyclerView自身的测量高度。
解决方案
因此,我们只需要重写LayoutManager的public void setMeasuredDimension(Rect childrenBounds, int wSpec, int hSpec)方法即可为RecyclerView设置最大宽高。
1 | recyclerView.layoutManager = object : LinearLayoutManager(context, RecyclerView.VERTICAL, false) { |
作者:猫爸iYao
链接:https://www.jianshu.com/p/0dec79ff70df
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。