Search code examples
androidandroid-fragmentsandroid-viewbinding

View binding does not have access to fragment


I have an activity with ConstraintLayout and fragment on it:

<androidx.constraintlayout.widget.ConstraintLayout 
 ...attributes....
>
  <fragment
     android:id="@+id/containerView"
     app:navGraph="@navigation/some_navigation"
     ...other attributes...
   />

  ...other views...

I'm using view binding in the activity code:

  binding = ActivityMainBinding.inflate(layoutInflater)

the issue here that i have no access to the binding.containerView. Does in case of fragment I should use findViewById ?


Solution

  • Fragment tag ( <fragment>) is not a view it act as a container for other views, So you cannot access it like other views...

    You will get compilation error when you try to access a non-view element using binding

    Instead you can use,

    supportFragmentManager.findFragmentById(R.id.containerView)