简体   繁体   中英

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 View s 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!

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 !

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM