Kotlin开发RecyclerView报No adapter attached; skipping layout不展示数据问题
问题原因
你遇到的报错和渲染异常是两个核心问题导致的:
No adapter attached报错是因为RecyclerView初始化时没有绑定Adapter,你把Adapter的创建和绑定全放在异步网络请求的回调里,页面首次绘制时RecyclerView找不到Adapter就会抛出该警告。- 列表不展示/展示异常是因为你贴出的商品卡片布局和RecyclerView所在页面布局完全重复,你把承载RecyclerView的页面布局当成了列表item布局来用,item根布局高度设为match_parent会导致单个商品占满整个屏幕,看不到后续内容。
修复步骤
1. 修正商品卡片item布局
你需要新建单独的列表item布局(比如命名为item_product.xml),不要和RecyclerView所在页面布局混用,示例代码如下:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16dp"> <ImageView android:id="@+id/productImage" android:layout_width="100dp" android:layout_height="100dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="16sp" android:textStyle="bold" app:layout_constraintStart_toEndOf="@+id/productImage" app:layout_constraintTop_toTopOf="@+id/productImage" android:layout_marginStart="16dp"/> <TextView android:id="@+id/price" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="14sp" android:textColor="@android:color/darker_gray" app:layout_constraintStart_toEndOf="@+id/productImage" app:layout_constraintTop_toBottomOf="@+id/name" android:layout_marginStart="16dp" android:layout_marginTop="8dp"/> </androidx.constraintlayout.widget.ConstraintLayout>
注意item根布局高度要设为wrap_content,不要用match_parent
2. 优化Adapter和Activity初始化逻辑
提前初始化Adapter绑定空列表,网络请求拿到数据后再更新Adapter内容,解决无Adapter的报错:
修正后的Adapter代码:
package com.mlp.project.utils import android.content.Context import android.view.LayoutInflater import android.view.View import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.mlp.project.api.model.Product import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.mlp.project.R class MyAdapter(val context: Context, var productList: List<Product> = emptyList()): RecyclerView.Adapter<MyAdapter.ViewHolder>(){ class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val name: TextView = view.findViewById(R.id.name) val price: TextView = view.findViewById(R.id.price) val productImage: ImageView = view.findViewById(R.id.productImage) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { // 加载刚才新建的item_product布局 val itemView = LayoutInflater.from(context).inflate(R.layout.item_product, parent, false) return ViewHolder(itemView) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val product = productList[position] holder.name.text = product.name holder.price.text = "¥${product.price}" // 拼接图片域名加载图片 val imageUrl = "https://katobackend.azurewebsites.net/${product.productImage.replace("\\", "/")}" Glide.with(context) .load(imageUrl) .into(holder.productImage) } override fun getItemCount(): Int = productList.size // 新增更新数据的方法 fun updateData(newList: List<Product>) { productList = newList notifyDataSetChanged() } }
注:图片加载需要先导入Glide依赖,在模块级build.gradle的dependencies中添加implementation 'com.github.bumptech.glide:glide:4.16.0'、kapt 'com.github.bumptech.glide:compiler:4.16.0'
修正后的Activity代码:
class Authenticated : AppCompatActivity() { private lateinit var sessionManager: SessionManager private lateinit var apiClient: ApiClient private lateinit var myadapter: MyAdapter private lateinit var linearLayoutManager: LinearLayoutManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_authenticated) recyprod.setHasFixedSize(true) linearLayoutManager = LinearLayoutManager(this) recyprod.layoutManager = linearLayoutManager // 提前初始化Adapter绑定空列表 myadapter = MyAdapter(this) recyprod.adapter = myadapter fetchPosts() } private fun fetchPosts() { apiClient = ApiClient() sessionManager = SessionManager(this) apiClient.getApiService().fetchPosts(token = "${sessionManager.fetchAuthToken()}") .enqueue(object : Callback<ProductResponse> { override fun onFailure(call: Call<ProductResponse>, t: Throwable) { Log.d("Authenticated", "onFailure: ${t.message}") } override fun onResponse(call: Call<ProductResponse>, response: Response<ProductResponse>) { Log.d("Response", response.toString()) response.body()?.let { body -> // 更新Adapter数据 myadapter.updateData(body.products) } } }) } }
3. 其他优化点
- 你之前的RecyclerView宽高写了固定的409dp、729dp,建议改为
match_parent适配不同尺寸的手机屏幕 - 网络请求失败时可以加空态、错误提示优化用户体验
内容的提问来源于stack exchange,提问作者therealwalim
相关产品推荐
相关产品推荐

