7

Is it possible to have data binding give me a reference to a fragment inside an activity layout?

My activity has a fragment within a FrameLayout, and I get the data binding like this:

fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val binding: ActivityUxBinding = DataBindingUtil.setContentView(this, R.layout.activity_ux)

The auto-generated ActivityUxBinding contains no member for the fragment so I still have to do this:

arFragment = supportFragmentManager.findFragmentById(R.id.ux_fragment) as ArFragment

Is there a way to get a member uxFragment of the type specified in the layout?

For reference, the activity's layout:

<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <fragment android:name="edu.htw.cd.ar.objectdetect.sceneform.ArFragmentWithoutInstructions"
            android:id="@+id/ux_fragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/search_fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|end"
            android:layout_margin="16dp"
            app:srcCompat="@drawable/ic_search"
            app:elevation="6dp" /> <!-- https://material.io/design/environment/elevation.html -->
    </FrameLayout>
</layout>
pezcode
  • 5,490
  • 2
  • 24
  • 37

0 Answers0