通过GreenRobot EventBus更新RecyclerView遇报错及解决
解决RecyclerView更新时"No adapter attached; skipping layout"问题
最近两天我一直在尝试用EventBus接收的数据更新RecyclerView,但始终卡在**"No adapter attached; skipping layout"**这个错误上。明明能正常收到EventBus的响应数据,却就是没法用来更新RecyclerView,急死个人。
我试过的方案
我翻了不少资料,试了几种常见的解决办法,但都没效果:
- 在Adapter里直接追加数据
- 在Adapter类中专门写了方法,试图通过EventBus来修改RecyclerView的条目
相关代码片段
EventBus订阅处理方法
@Subscribe(threadMode = ThreadMode.MAIN) fun pickDropChooseEvent (data : PickAddressDone){ try { // vehicleListResult是自定义的数据模型 vehicleListResult = data.vehicleListResult vehicleAdapter.updateData(vehicleListResult.vehicleCategory!!); vehicleAdapter.notifyDataSetChanged(); } catch (exception : Exception ) { Log.d("vehicle info" ,"catch pick drop "+exception.toString()) } }
Fragment视图初始化代码(在ViewCreated中调用)
private fun initMembers() { try{ vehicleList = ArrayList() vehicleList.addAll(vehicleListResponse.vehicleListResult!!.vehicleCategory!!) tvDistance.text = vehicleListResult.ride!!.distanceText rvVehicleList.setHasFixedSize(true) rvVehicleList.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) rvVehicleList.setAdapter(vehicleAdapter) vehicleAdapter = VehicleCategoryAdapter(context!!, vehicleList) // 我甚至还尝试在这里调用notifyDataSetChanged,但没用 }catch (exception: Exception) { Log.d("vehicle info", " exception "+exception) } }
最终解决:问题出在XML布局!
折腾了半天才发现,代码本身根本没毛病,问题出在包裹RecyclerView的ConstraintLayout布局上!
原来的ConstraintLayout设置了这些属性:
<androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_margin="@dimen/margin_2dp" android:background="@drawable/grey_shadow_background" app:layout_constraintBottom_toTopOf="@+id/clRideInfo" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintTop_toTopOf="parent" <!-- 这行是罪魁祸首!导致ConstraintLayout高度无法正确分配 --> app:layout_constraintStart_toStartOf="parent"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/rvVehicleList" android:layout_width="match_parent" android:layout_height="wrap_content" app:layoutManager="LinearLayoutManager" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" tools:listitem="@layout/layout_vehiclelist_item" /> </androidx.constraintlayout.widget.ConstraintLayout>
把那行导致ConstraintLayout高度无法正确分配的约束属性移除之后,RecyclerView就正常显示,并且能通过EventBus的数据更新了!
内容的提问来源于stack exchange,提问作者Amanpreet Kaur
相关产品推荐
相关产品推荐

