Reputation: 1697
I am working on a simple app to become acquainted with RecyclerView in Android. When overriding the onBindViewHolder method in my adapter, Android Studio does not recognize the id corresponding to the element to which it should bind data.
Layout Resource File (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>
Adapter Class:
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
}
}
Why isn't Android Studio recognizing the id of the element in the layout resource file? I have invalidated cache and restarted, I have also cleaned project and rebuilt.
Upvotes: 0
Views: 703
Reputation: 303
Try like this
CategoryAdapterHolder(LayoutInflater.from(parent.context).inflate(com.example.secondhand.R.layout.category_list, parent, false))
Not from android.R
Upvotes: 0
Reputation: 303
You have not added text view inside view holder class
inner class ListViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView){
val itemName = itemView.findViewById<TextView>(R.id.item_name) // this line
}
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.itemName.text = list[position]
}
Upvotes: 1
Reputation: 1697
Inside build.gradle (module) add the kotlin-android-extensions plugin:
plugins {
id 'com.android.application'
id 'kotlin-android'
id 'kotlin-android-extensions'
}
Upvotes: 1