Reputation: 1337
I added a ComposeView
in my XML layout file. I use view binding to inflate this file in my Activity. When I try to call binding.myComposeView.setContent { ... }
then I get the following compilation error: Unresolved reference: setContent
. When I take a look at the generated binding file, the type of myComposeView
is View
and not ComposeView
. When I use findViewById<ComposeView>(R.id.myComposeView).setContent { ... }
then everything works fine. Why is the binding not generated correctly? What can I do to use view binding with a ComposeView
?
Upvotes: 2
Views: 5696
Reputation: 1337
It turns out that I had two versions of the same layout: portrait and horizontal. I converted the portrait one to Compose by replacing a LinearLayout
with a ComposeView
. However, in the horizontal layout myComposeView
was still a LinearLayout
. That's why the view binding class that got created had a field myComposeView
of type View
instead of ComposeView
. The view with the same id had different types in two layout versions.
Upvotes: 6
Reputation: 535
Maybe there is a problem with the way the binding is set up in onCreate of your activity. Are you using something along the lines of the following code? :
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
binding.composeView.setContent {
MaterialTheme {
Text(text = "Hello World")
}
}
}
Upvotes: 0