Home > Mobile >  How to findViewById in RecyclerView after setting custom id to every element via adapter
How to findViewById in RecyclerView after setting custom id to every element via adapter

Time:12-13

I have a fragment that implements Recycler View with switches. RecyclerView sets id for every switch in id =1 way. The problem is I can get nothing from these IDs as soon as calling throws NullableException. I understand that I have to call it correctly from parent, but I don`t get how to do it correctly. There is the structure of code: Fragment with ConstraintLayout(R.id.settingsScreen) -> RecylerView(R.id.recyclerView), that creates LinearLayouts(R.id.settingLayout) with switches(R.id.switch).

class ViewHolder{
    val l : LinearLayout = view.findViewById(R.id.settingLayout)
}

if (holder.l.findViewById<SwitchCompat>(1100).isActivated){..}

throws java.lang.NullPointerException: Attempt to invoke virtual method 'boolean androidx.appcompat.widget.SwitchCompat.isActivated()' on a null object reference

CodePudding user response:

It is very fragile to create view IDs yourself like this. They could easily collide with IDs generated by the Android build. So if you create IDs, you should be using ViewCompat.generateViewId() to do it safely.

But findViewById is something you generally want to avoid in the first place. It is slow. That's why View Binding is provided, to cache the views so you don't have to keep searching for them.

I highly recommend storing your Views in a collection instead of assigning them IDs. Then you can efficiently pull them from the collection when you need them. You just need to be sure the collection will be garbage collected when you're done with the views (don't create a collection that will outlive the screen the views are on).

CodePudding user response:

You can get the view by using itemView property

Not sure of you are trying to do when you mean custom id.


You can get all views inflated by viewHolder with itemView.

this property is given to ViewHolder after you pass view as parameter in ViewHolder constructor, than ViewHolder will inflate views according with their id's.

than you can get view inside ViewHolder by:

itemView.findViewById<LinearLayout>(R.id.settingLayout)

itemView.findViewById<SwitchCompat>(R.id.switch)

You can look to see more options in google docs

If these are not what you asked for please let me know

  • Related