【发布时间】:2022-01-15 02:22:29
【问题描述】:
我正在开发一个简单的应用程序来熟悉 Android 中的 RecyclerView。在我的适配器中覆盖 onBindViewHolder 方法时,Android Studio 无法识别与其应绑定数据的元素对应的 id。
布局资源文件(list_item.xml):
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
android:id="@+id/item_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
适配器类:
class ListAdapter(private var list: List<String>)
: RecyclerView.Adapter<ListAdapter.ListViewHolder>(){
inner class ListViewHolder(itemView : View)
: RecyclerView.ViewHolder(itemView)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.list_item, parent, false)
return ListViewHolder(view)
}
override fun onBindViewHolder(holder: ListViewHolder, position: Int) {
holder.itemView.apply {
item_name.text = list[position] // item_name is unresolved reference
}
}
override fun getItemCount(): Int {
return list.size
}
}
为什么 Android Studio 不能识别布局资源文件中元素的 id?我已经使缓存失效并重新启动,我还清理了项目并重建了。
【问题讨论】:
标签: android android-studio android-recyclerview