36

I know that this question have been asked before but I tried all the answers given and I still got nothing. I'm trying to define a var binding:ActivityMainBinding and I got an error

Unresolved reference:ActivityMainBinding

Here is a part of my mainActivity

import com.kolydas.aboutme.databinding.ActivityMainBinding //error

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding //error
    //....
}

Here is my App build.gradle

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'    
apply plugin: 'kotlin-kapt'    
apply plugin: 'kotlin-android-extensions'   

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.kolydas.aboutme"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    dataBinding{
        enabled = true  //enable data binding
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    kapt "com.android.databinding:compiler:3.4.0"
}

And of course in my xml file i have the layout /layout tags in the beginning and in the end.

Martin Brisiak
  • 3,872
  • 12
  • 37
  • 51
Alex
  • 1,816
  • 5
  • 23
  • 39
  • please try like this "val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)" – android May 01 '19 at 08:48
  • @android doesn't work.Something is wrong with the libraries i believe because also in my imports i got the error(on the line i import the ActivityMainBinding) – Alex May 01 '19 at 08:50
  • 1
    have you imported the "import android.databinding.DataBindingUtil"? – android May 01 '19 at 08:51
  • please update your library with "com.android.databinding:compiler:3.5.0-alpha13" – android May 01 '19 at 08:52
  • What gradle version are you using? – Leo May 01 '19 at 08:54
  • 3
    Did you try rebuilding your project? – Rahul Agrawal May 01 '19 at 09:15
  • a. Does your xml file have the layout tag enclosing everything else? Without it, no binding class will be created. Also: try to comment out that line and build the app, maybe the binding class hasn't been built yet – fweigl May 01 '19 at 09:30
  • @RahulAgrawal wow that was it :O – Alex May 01 '19 at 09:46
  • 3
    I have faced similar issue before and had read somewhere that the databinding file is created only on successful compile of the application. Glad i was of some help. @AlexKolydas – Rahul Agrawal May 01 '19 at 09:47
  • I had similar challenge, after some time it worked. I think you should also put on your internet connection – rugue Jun 06 '19 at 22:22

21 Answers21

45

None of the suggestions worked for me, because the correct way to resolve this issue is to put (app level build.gradle)

buildFeatures{
   dataBinding = true
   viewBinding = true
}
Android
  • 1,529
  • 1
  • 12
  • 27
18

Sometimes all you need is clean and rebuild the project.

Build -> Clean Project 
Build -> Rebuild Project

This would be enough for generating the binding classes.

Generated binding classes

hivana
  • 312
  • 2
  • 5
14

Try to add in build.gradle (Module:app)

buildFeatures {
   viewBinding true
}
Ika
  • 302
  • 2
  • 3
7

I see this relatively old bug every now and then (regardless of using kotlin or not, but it's very common when you convert a class from java to kotlin) and it's still an issue with the newest android studio. Cleaning the project does not help in many cases. Whenever there seems to be no valid reason for this issue, following trick always solves the issue for:

Solution 1

Rename the xml file (e.g. main_activity2.xml), clean the project and try to do change MainActivityBindingtoMainActivity2Binding`

Solution 2 (I just found this trick recently but it seems to work reliably as well)

Alternatively make a change inside the problematic xml file (add a view or so or change an attribute), clean the project and it's working again.

Background

I see this happening when moving layouts between modules e.g. and sometimes in other cases as well. But refactoring the structure regularly results in this issue. There is some caching problem that leads to this problem sometimes and in many cases, even deleting all temp files and cleaning the project does not help but only changing the xml or renaming it does solve the issue...

prom85
  • 16,896
  • 17
  • 122
  • 242
4

It's not about the Gradle file. It is about the XML file.

First, make sure that your layout tag contains just this line:

xmlns:android="http://schemas.android.com/apk/res/android"

or these lines:

xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"

Then rebuild the project.

grooveplex
  • 2,492
  • 4
  • 28
  • 30
Abdelaziz refaat
  • 157
  • 1
  • 12
  • 1
    I had layout_height and width on my Layout root node, but when only namespace attributes where left, the system proposed me to convert it to databinding layout. I cleaned and rebuild project, and the problem got solved. – Bardo Apr 20 '20 at 16:24
  • In my case I had the wrong context on the xml file. Thanks. – Dieglock Dec 16 '21 at 09:45
3

Just to sum up all useful actions:

  1. Check if you got top-level <layout> tag in respective .xml file.
  2. Verify build.gradle (app) if binding enabled=true in android section.
  3. Verify imports in activity file:

    import android.databinding.DataBindingUtil
    import com.example.[YOUR_APP_NAME].databinding.ActivityMainBinding
    
  4. Try to rebuild project Build > Rebuild Project after every action just to refresh and check the results.

    Good Luck! It's just beginning of this Android journey:)

RobC
  • 22,977
  • 20
  • 73
  • 80
Rob Ert
  • 442
  • 5
  • 23
3

Faced similar issue while following the Android Udacity Lessons Creating and Adding Fragment.

In my case the TitleFragment class was unable to resolve com.example.android.navigation.databinding.FragmentTitleBinding.

I had to add empty <data></data> tag in fragment_title.xml file and clean/rebuild the project for the compilation error to go away.

pshirishreddy
  • 746
  • 6
  • 20
  • 1
    in case someone needs to see the code here is the github link https://github.com/udacity/andfun-kotlin-android-trivia/blob/Step.01-Exercise-Creating-and-Adding-a-Fragment/app/src/main/java/com/example/android/navigation/MainActivity.kt – TarekB Dec 16 '19 at 16:18
3

Here is what I did. Step 1. Go to build.gradle(Module:app), add this in android , below buildTypes:

buildFeatures {
        dataBinding true
    }

Step 2. In activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<layout>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
</androidx.constraintlayout.widget.ConstraintLayout>
<!--you can add some xml tag here-->
</layout>

Step 3. In MainActivity.kt (testapp is my project)

import androidx.databinding.DataBindingUtil
import com.example.testapp.databinding.ActivityMainBinding

Step 4.

Go to Build->Clean Project 
and then Rebuild Project
pharask
  • 322
  • 7
  • 15
3

set in build.gradle(app) :

android
{
buildFeatures
 {
 dataBinding = true
 viewBinding = true
 }
}
Mark Nashat
  • 668
  • 8
  • 9
  • 2
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – mufazmi May 21 '21 at 18:17
3

Update, due to version '7.2.0'

after add

buildFeatures {
        viewBinding = true
        dataBinding = true
    }

then in Xml

xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity"

Finally , must add the name of the layout (XML) file

import com.src.example.databinding.NameOfXML

for example:

R.layout.new_face -----> NewFaceBinding 

then in Activity

 val binding  = NewFaceBinding.inflate(layoutInflater)
        setContentView(binding.root)

Moreover the id calling also is changed

in xml

android:id="@+id/progress_bar2"

in Activity

binding.progressBar2.
Mori
  • 2,653
  • 18
  • 24
3

copy this code in your build.gridle(:app) in buildTypes section and then click sync now below the file window tab.Then do Build -> Rebuild Project

Note: There is no = sign after dataBinding

buildFeatures{
   dataBinding  true
   viewBinding = true
}
zircon
  • 742
  • 1
  • 10
  • 22
2
kapt "com.android.databinding:compiler:3.4.0"

change to

kapt 'androidx.databinding:databinding-compiler-common:3.4.0'
Viktor
  • 21
  • 3
2

Just add import com.example.tiptime.databinding.ActivityMainBinding in your MainActivity.kt file

2

I just want to contribute my answer here, so a person who's scrolling can try the different options. This finally worked for me:

After adding databinding enabled in app gradle file, you add the tags in the layout xml right? Ensure that it is "<layout>" not "<Layout>" (lowercase not uppercase).

Also whichever is the base viewgroup in your layout, you can simply click the bulb that you get when you hover over its name, and click on "convert to data binding", it'll add the right tags for you. THEN you can try to get the ActivityMainBinding class in your activity (if it doesn't work try rebuilding once)

A B
  • 189
  • 2
  • 9
2

Summary:

Assuming that you already setup your setup the data binding and/or view binding in build.gradle (app) as explained others answers in this post...

When you change the name of your activity, the name of the binding must changes too.

For example: If you change the name of your activity from MapsActivity to SomeMapsActivity then your import changes from:

import com.myexample.exampleapp.databinding.ActivityMapsBinding

to:

import com.myexample.exampleapp.databinding.ActivitySomeMapsBinding

This means that you must go thorough the code and change it there too:

From:

private lateinit var binding: ActivityMapsBinding

To:

private lateinit var binding: ActivitySomeMapsBinding

From:

binding = ActivityMapsBinding.inflate(layoutInflater)

To:

binding = ActivitySomeMapsBinding.inflate(layoutInflater)

Description:

I encounter this issue when I tried to have two different Maps activities by duplicating an existent one.

First, you need to make sure that each Map activity has its own layout.

In my case, more than a layout, its a FragmentContainerView:

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

Please notices tool:context since that value must indicate what activity is this fragment binding with. In my case, both FirstMapActivity and SecondMapActivity are both inside the ui package.

Next, look into the imports of each Map activity.

ActivityMapsBinding is in red, isn't it?. That's because it isn't the right binding.

import com.myexample.exampleapp.databinding.ActivityMapsBinding

Since you changed the name of the map activity, the name of the binding binding changed name too.

In my case, on the first map, it changes from:

import com.myexample.exampleapp.databinding.ActivityMapsBinding

to:

import com.myexample.exampleapp.databinding.ActivityFirstMapsBinding

On the second map, it changes from

import com.myexample.exampleapp.databinding.ActivityMapsBinding

to:

import com.myexample.exampleapp.databinding.ActivitySecondMapsBinding
acarlstein
  • 1,799
  • 2
  • 13
  • 21
2

If you can not access to ActivityMainBinding in MainActivity.kt

  1. Problem ⛔

    If you you call ActivityMainBinding Type in MainActivity.kt without adding in your activity_main.xml, ActivityMainBinding will be not read it in MainActivity.kt

  2. Solution ✅

    2.1. enabled dataBinding in build.gradle (App)

    2.2. add in your activity_main.xml

    2.3. call ActivityMainBinding in your MainActivity.kt

  3. Warning ⚠️

    You don't need call viewBinding in in build.gradle (App)

  4. Overview example ️ enter image description here

1

In my project, if you don’t wrap activity_main.xml in root element layout, data binding doesn’t work...

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

<layout>

<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<androidx.recyclerview.widget.RecyclerView
android:id="@+id/resycler_data"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

</layout>
  • Please avoid images of code! You can format code in your answer with the {} button – B. Go Mar 24 '20 at 22:44
  • For some questions about unresolved FragmentTitleBinding, please try to replace the default tag with tag in your res/layout/fragment_title.xml – user1283182 Apr 07 '20 at 03:05
1

Your xml must started as :

<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"> 
0

A binding class is generated for each layout file. The default naming convention used for the generated class is based on the name of the layout file. It converts the layout name to Pascal case notation and will be adding a Binding suffix to that. If the layout filename is activity_main.xml so the corresponding generated class is named as ActivityMainBinding. This class holds all the bindings info. Source: Databinding in Android

gresolio
  • 966
  • 10
  • 16
0

Finally solved this error with the fourth line.

activity_main.xml

package com.example.<your-project-name>

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.<your-project-name>.databinding.ActivityMainBinding // <---- Add this line

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)

Make sure the file name creates the object automatically.

  • activity_main.xml -> ActivityMainBinding
  • result_profile.xml -> ResultProfileBinding

ref. https://developer.android.com/topic/libraries/view-binding

kujiy
  • 5,833
  • 1
  • 29
  • 35
0

one of the reasons you will see this error if you are using tools:viewBindingIgnore="true" in the layout.xml file mistakenly.

Yousuf Qureshi
  • 498
  • 2
  • 7
  • 21