So i have been following this tuitorial and for soem reason I can not import my text from xml to kotlin file. I have tried diffrent things but it still wont work.
I did add id 'kotlin-android-extensions' to my gradle:module:app but still wot go though.
Here is my code
todoAdapter.kt `
package com.example.todo
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.view.menu.ActionMenuItemView
import androidx.recyclerview.widget.RecyclerView
class todoAdapter(
private val todos : MutableList<Todo>
):RecyclerView.Adapter<todoAdapter.TodoViewHolder>() {
class TodoViewHolder(itemView:View): RecyclerView.ViewHolder(itemView)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TodoViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_todo,parent,false);
return TodoViewHolder(view);
}
override fun onBindViewHolder(holder: TodoViewHolder, position: Int) {
val curTodo = todos[position]
holder.itemView.tv (this bracket is not included in the code, the reason i onyl wrote tv is that if i wrote full it would be a red text and not get thr refrence)
}
override fun getItemCount(): Int {
return todos.size;
}
}
`
item_todo.xml
`
<?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="70dp"
android:paddingStart="14dp"
android:paddingEnd="14dp">
<TextView
android:id="@ id/tvTodoTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Example"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<CheckBox
android:id="@ id/tvCheckboxTodo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
`
I have tried using the apply but that funciton too doesnt seem to work , I just wanna know where I am doing htinsg wrong. Please expalin begnier level as I am still lenring
CodePudding user response:
I think you meant to do this:
class TodoViewHolder(itemView:View): RecyclerView.ViewHolder(itemView) {
val tvTodoTitle: TextView = itemView.findViewById(R.id.tvTodoTitle)
val tvCheckboxTodo: Checkbox = itemView.findViewById(R.id.tvCheckboxTodo)
}
Then in your onBindViewHolder
you can do
holder.tvTodoTitle.text = "Whatever you want"
CodePudding user response:
You must create the reference first then you can call it later. You can create tvTodoTitle
in the body of class TodoViewHolder
by the following code:
TextView tvTodoTitle = itemView.findViewById(R.id.tvTodoTitle);
then in onBindViewHolder
you can call the tvTodoTitle
reference:
holder.itemView.tvTodoTitle ...