getActivity() / context in a ViewHolder in Kotlin Android
In your implementation you can safely use Context
from View
provided to your OnClickListener
override fun onClick(p0: View) {
Toast.makeText(p0.context, "${mCrime!!.mTitle} clicked!", Toast.LENGTH_SHORT / 2)
.show()
}
Just remember to set onclick:
fun bind(crime: Crime) {
mCrime = crime
val titleTextView = itemView.findViewById<TextView>(R.id.crime_title)
val dateTextView = itemView.findViewById<TextView>(R.id.crime_date)
titleTextView.text = mCrime!!.mTitle
dateTextView.text = mCrime!!.mDate.toString()
itemView.setOnClickListener(this)
}
Moreover all Kotlin classes are nested (static
) by default. So your private class CrimeHolder
is equivalent to private static class CrimeHolder
in Java. That's why you don't have access to getActivity()
from within CrimeHolder