Home > Enterprise >  How to import data-binding in Android app (Java)?
How to import data-binding in Android app (Java)?

Time:05-05

I had imported data-binding package in another application but, now I am trying to copy paste the same file in another project its showing an error!

I have enabled dataBinding in android in build.gradle (app level) as:

android {
    dataBinding {
        enabled = true
    }
}

activity_maps.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.fragment.app.FragmentContainerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@ id/google_map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapsActivity">

</androidx.fragment.app.FragmentContainerView>

I know that we need to convert layout in .xml file as dataBinding type but, I had used the same code (only package was different).

MapsActivity.java:

package com.Inchargenext.loginactivity;

import com.Inchargenext.loginactivity.databinding.ActivityMapsBinding;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
    private ActivityMapsBinding binding;
}

Here I can't import the databing or create ActivityMapsBinding object as import is necessary.

CodePudding user response:

I was able to succefully import the databing file after editing the build.gradle's android's buildFeatures as:

buildFeatures {
    dataBinding = true
    viewBinding = true
}

Also, make sure above, and below code is written in app level build.gradle:

dataBinding {
    enabled = true
}

CodePudding user response:

If you want to use databinding in your Java (or Kotlin) classes, you have to change your XML like this:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@ id/google_map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapsActivity">

</layout>

Then, you will be able to do private ActivityMapsBinding binding; And import that binding variable.

Also, check this codelab, because if you understand how it does work will help you in the future.

  • Related