cheaze
cheaze

Reputation: 187

How do I set View ids when accessing children of View when using ViewBinding instead of Kotlin Synthetics?

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!

EDIT

I have another case that's a bit confusing.

binding.formItems.children
        .filter { it.getTag(R.id.tag_guest_identifier) != null }
        .map { view ->
            Guest(
                guestIdentifier = view.getTag(R.id.tag_guest_identifier).toString(),
                name = view.playerName.valueText.toString(),
                ...
            )
        }
}

Here, I get a list of generic Views so I can't access their properties (ie. view.playerName... etc.).

Do I need to create a View subclass and then cast the view to that type? Is there an easier way to achieve this?

Thanks again!

Upvotes: 0

Views: 558

Answers (2)

cactustictacs
cactustictacs

Reputation: 19524

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!

Upvotes: 1

Roberto Fortunato
Roberto Fortunato

Reputation: 89

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

Upvotes: 0

Related Questions