Search code examples
androidandroid-recyclerviewtextview

is it bad practice to findViewById in onBindViewHolder?


i'm working on a recyclerView implementation in Android. here is my Adapter's onBindViewHolder method:

// Replace the contents of a view (invoked by the layout manager)
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
    // - get element from your dataset at this position
    // - replace the contents of the view with that element
    val textView = holder.textView.findViewById(R.id.simple_text) as TextView
    textView.text = myDataset[position]
}

so basically the MyViewHolder class has a View field called textView (which is actually a layout from my res/layout folder) and i access the TextView (which is a child of textView in the layout) using findViewById. is this bad practice? should we avoid calling findViewById in the onBindViewHolder function?

thanks


Solution

  • It is perfectly valid, and not a bad practice. Although you may add some optimization by caching a local reference of the child views inside your ViewHolder class implementation for faster access, but is up to you and will depend on your design requirements.

    A side note: I would rename your ViewHolder's textView field to something more meaningful as maybe itemLayout or something else, to make it more clear that is referring to an actual layout and not a TextView widget. As you see there is already a different answer from someone else who didn't fully read your question, and got confused believing your textView field refers to the ViewHolder's itemView.