What you need to do here is to create a property for your TextView inside your ViewHolder. This isn't particularly easy with Anko, but here are some ways to do it.
1. Pass every View you want be able to reference from your ViewHolder as a separate constructor parameter.
For this solution, you have to modify your ViewHolder class like this, adding a property for the TextView:
class ViewHolder(view: View, val mTextView: TextView) : RecyclerView.ViewHolder(view)
You can initialize this property in this slightly convoluted way:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Adapter.ViewHolder {
lateinit var mTextView: TextView
val view = ctx.UI {
relativeLayout {
mTextView = textView("1 + 1 = 2")
}
}.view
return ViewHolder(view, mTextView)
}
While this doesn't look very nice, you're keeping the reference to your TextView from when you're initially creating it, so it's efficient.
2. Give your Anko created View instances IDs and look them up by their IDs later.
First, you have to create constants for your IDs - the ID can be any positive number, just make sure they're unique within the scope you're using them. One way is to place these inside a companion object, like so:
companion object {
private const val TEXT_VIEW_ID = 123 // Arbitrary positive number
}
Then, you need to give this ID to your TextView:
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Adapter.ViewHolder {
return ViewHolder(ctx.UI {
relativeLayout {
textView("1 + 1 = 2") {
id = TEXT_VIEW_ID
}
}
}.view)
}
Finally, you can find your TextView again in your ViewHolder class with findViewById:
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val mTextView: TextView = view.findViewById(TEXT_VIEW_ID)
}
Of course this is going to be slower, because you're losing the TextView reference you already had when you're passing in the View to the ViewHolder, and then you're looking it up again.
Note that I stuck with mTextView for the answer so that it's easier to follow, but it's generally not recommended to use Hungarian notation or any other name prefixes in Kotlin.