I am updating an Android project to use ViewBinding
instead of Kotlin Synthetics
. I'm having difficulty figuring out how to change the following code so I can access the views from their layout IDs.
binding.myLinearLayout.children
.filter { it.checkboxInput is CheckBox }
In this case children
are all generic View
types and can't access the checkboxInput
IDs like it used to be possible using Kotlin Synthetics
.
I get the error Unresolved reference: checkboxInput
What would be the way to solve this? Is there a way to check if the View is of a binding type? Do I need to make custom View classes to do this? Any other ideas?
Thanks for your help!
CodePudding user response:
With viewBinding you can access views typing just
binding.viewId
Where viewId is the id defined for each view in your xml with the attribuite
android:id
In your case you can access the checkbox using
binding.checkboxInput
CodePudding user response:
View binding works basically the same way synthetics did, except when you have something with an ID of checkbox_input
, instead of magically creating a variable called checkboxInput
on the Activity
or whatever, it creates it in the ViewBinding
object instead. So if you were accessing it like this before:
// not declared anywhere, it's just magically there for you to use
checkboxInput
now you access it on the ViewBinding
object instead:
binding.checkboxInput
You don't need to do any searching, that defeats the point of view binding! It's automagically binding views to variables in a convenient object.
Your code would work with filter { it is CheckBox }
, and then you'd get all the Checkbox
items within that part of the layout (you can also use filterIsInstance<CheckBox>
, same thing). But if you wanted the one with a specific ID, you'd have to look at its ID attribute - and at that point, might as well just use findViewById
!