简体   繁体   中英

Trouble enabling viewBindings (kotlin)

I have not adhered to the Single Activity Schema and have multiple Activities in my application. All examples I can find using expandableListView require bindings.

I have:

1.)

buildFeatures {
            viewBinding = true
        }

2.) The layout tag within my xml

I have also tried using the include tag I found in some tutorial but

 val binding = ProfileActivityBinding.inflate(layoutInflater)

is not resolving to a binding. Am I misinterpreting how to use this?
Any tips are appreciated


I should note that within MainActivity.kt attempting to assign MainActivityBinding does not work either.

When you have view binding enabled, for every layout XML you have, it'll generate a binding class named after it. So if you have profile_activity.xml , it'll generate a class called ProfileActivityBinding . An instance of that class will have a variable for each View in your layout that has an ID (named similarly, but it does some conversion from snake case - eg my_button will be called myButton )

You can get an instance of this class by either calling its inflate method, or the bind one. inflate will inflate the profile_activity XML file into a view hierarchy, bind allows you to pass in one that's already been inflated (eg an Activity or Fragment 's view ).

You can use whichever one's convenient - if you need to inflate one anyway (say if you're creating a ViewHolder for a RecyclerView ) you may as well use inflate . Otherwise bind will take an existing hierarchy and look up all the views it needs to. Either way, you end up with a variable for each ID in the layout, and each one points to the actual View in that hiearchy, as though it did findViewById for each one.

If all that makes sense, and it's still not working, try building your app (you can just do Rebuild in the Build menu). The binding classes should be automatically generated when you create a layout, and the code editor should recognise them pretty much immediately, but sometimes it needs a kick. Might need to do a Clean or Invalidate Caches / Restart if it's playing up

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