You are using ArrayAdapter
. If you are going to use adapters, you should use RecyvlerView.Adapter
. Since you are learning, this is a perfect point to scratch that and learn Compose instead, with that out of the way.
The interface solution is the correct solution:
interface MyAdapterCallback {
fun onButtonClicked(clickCount: Int)
}
Then implement it in your activity
class MyActivity : ..., MyAdapterCallback {
override fun onButtonClicked(clickCount: Int) {
findViewById<TextView>(R.id.textView).setText("$clickCount")
}
}
You have to pass it to your adapter, this should be the same for array adapter or recycler, because is passing it in the constructor and then using it.
class Adapter(
...,
private val callback: MyAdapterCallback
) {
...setOnClickListener{
int ++ //this will work as long as int here is a valid thing
callback.onButtonClicked(int)
}
}
You might see this pattern with the delegate
naming instead, I'm using callback just to try to make it clearer.
Another dirty solution would be to, pass the view to the adapter.
class Adapter(
...,
private val myView: TextView
) {
...setOnClickListener{
int ++ //this will work as long as int here is a valid thing
myView.text = "$int"
}
}
That is a very bad solution because it breaks the separations of concern principle, you should use it only for debugging.
Finally, the problem that you are currently having is this:
View(myContext).findViewByID<TextView>(R.id.textView).setText("$var")
That is instantiating a new View
and inside that View
you are trying to find the R.id.textView
, that view is completely new so it has nothing inside. Your R.id.textView
is in the activity layout, a completely different view. So the method findViewByID
returns null
. However you declare that the method should found non null TextView
that why it crashes, if you change it to TextView?
then it will be handle as nullable and it won't crash, but is pointless because it doesn't exist. The method findViewByID
doesn't search in every place, just inside the View
you are accessing.