Can't figure out how to use viewbinding in my fragment

Issue

I try to implement the following fragment in my app.

import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.jiangdg.ausbc.base.CameraFragment
import com.jiangdg.ausbc.widget.AspectRatioTextureView
import com.jiangdg.ausbc.widget.IAspectRatio

class DemoFragment : CameraFragment() {
    private lateinit var mViewBinding: DemoFragmentBinding

    override fun initView() {
        super.initView()
    }

    override fun getCameraView(): IAspectRatio {
        return AspectRatioTextureView(requireContext())
    }

    override fun initData() {
        super.initData()
    }

    override fun getCameraViewContainer(): ViewGroup {
        return mViewBinding.cameraViewContainer
    }

    override fun getRootView(inflater: LayoutInflater, container: ViewGroup?): View {
        mViewBinding = DemoFragmentBinding.inflate(inflater, container, false)
        return mViewBinding.root
    }

    override fun getGravity(): Int = Gravity.TOP
}

but the DemoFragmentBinding is not recognized by android studio:
I get the following error :

Unresolved reference: DemoFragmentBinding

I think the problem is coming from the XML, I tried with the one on the android Docs

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" >
    <TextView android:id="@+id/DemoFragment" />
    <ImageView android:cropToPadding="true" />
</LinearLayout>

But it doesn’t change anything

I tried several xml found over the internet but no of them worked.
I’m not sure if the xml is the problem, and my question may be dumb, but can someone give me a lead to the good direction?

Edit: I forgot to explain: I have already put this in my app gradle

android {
    buildFeatures {
        dataBinding true
        viewBinding = true
    }

Solution

Firstly:

android {
    buildFeatures {
        dataBinding true
        viewBinding = true
    }

This is not correct, viewBinding is a part of dataBinding, so enabling "both" (separately) at the same time is… strange, judging on your title you want to use viewBinding only, so change the code above to:

android {
    buildFeatures {
        viewBinding true
    }

Then, if you sync your project, clean and rebuild it you should be able to reference binding variables inside of your fragments / activity (sometimes the Binding variables are not created after the build, that’s why you would need to clean and rebuild))

Answered By – JustSightseeing

Answer Checked By – David Goodson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *