22

I am trying to use a companion object property inside the layout but the compiler doesn't recognise it.

Kotlin Class

class MyClass {
  companion object {
    val SomeProperty = "hey"
  }
}

XML Layout

<layout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:fancy="http://schemas.android.com/tools">

  <data>
    <import type="package.MyClass"/>
  </data>

  <TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="@{MyClass.Companion.SomeProperty}"/>

</layout>

And I got this error:

e: java.lang.IllegalStateException: failed to analyze: android.databinding.tool.util.LoggedErrorException: Found data binding errors.
****/ data binding error ****msg:Could not find accessor package.MyClass.Companion.SomeProperty file:/path/to/my/layout.xml loc:21:67 - 21:103 ****\ data binding error ****

    at org.jetbrains.kotlin.analyzer.AnalysisResult.throwIfError(AnalysisResult.kt:57)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules(KotlinToJVMBytecodeCompiler.kt:138)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:154)
    ...
Caused by: android.databinding.tool.util.LoggedErrorException: Found data binding errors.
****/ data binding error ****msg:Could not find accessor package.MyClass.Companion.SomeProperty file:/path/to/my/layout.xml loc:21:67 - 21:103 ****\ data binding error ****

    at android.databinding.tool.processing.Scope.assertNoError(Scope.java:112)
    at android.databinding.annotationprocessor.ProcessDataBinding.doProcess(ProcessDataBinding.java:101)
    at android.databinding.annotationprocessor.ProcessDataBinding.process(ProcessDataBinding.java:65)
    ...

I've tried to use companion instead of Companion, but no luck.

Is it possible to use companion objects on xml layout with databinding? How can I proceed? Thanks in advance for any help :)

2
  • 1
    what is the context? why would you want this
    – Tim
    Jun 20, 2018 at 14:20
  • Well, I want to have a if that compares a value to a constant, like: android:visibility="@{delivery.status == Status.Companion.finished ? View.VISIBLE : View.GONE}" I don't know, I just made it up, but something like this
    – melanke
    Jun 20, 2018 at 17:41

7 Answers 7

24

In order to access Companion object attributes and methods, it is NOT required to have an instance of the Parent object. Companion object are already instantiated, therefore you can access the instance directly.

Instead of using <import> (which is the natural translation from Java), we need to use <variable>, because we actually want to use the (already instantiated) Companion object into our XML Layout.

Import your Companion object as follow

Given Kotlin class:

package com.example.project

class MyViewModel {
    companion object {
        // it is only working with val and var
        // const val wouldn't work
        val MAX_LENGTH = 10
    }
}

Layout:

    <data>
        <!-- Declare your "variable" that hold the Companion object itself -->
        <variable name="myViewModelStatic" type="com.example.project.MyViewModel.Companion" />
    </data>

    <!-- then use the myViewModelStatic to access "static" properties of MyViewModel -->
    <EditText
    ...
    android:maxLength="@{ myViewModelStatic.MAX_LENGTH }"
    />
</layout>

Fragment:

class MyFragment {
    ...
    onViewCreated(...) {
         // now bind the companion object to the variable declared in the XML
         binding.myViewModelStatic = TransferUseCase.Companion
    }
    ...
}
1
  • This is only the answer. Thank you.
    – MJ Studio
    Apr 17, 2019 at 5:40
11

You can get rid of Companion keyword if you annotate your method/proprty with @JvmStatic

6

In the XML just add Companion before the name of the field, for example:

In ViewModel

package com.example.project

class MyViewModel {
    companion object {
        var leText = "text"
    }

    var leColor = ...
}

In XML

<data>
    <import type="android.view.View" />
    <variable 
        name="context"
        type="com.example.project.MyViewModel" />
</data>

<TextView
    ...
    android:text="@{context.Companion.leText}"
    android:color="@{context.leColor}"/>
1
  • I don't have an instance :(
    – melanke
    Aug 1, 2018 at 12:38
2

To get access to your property, do the following:

Annotate you companion object property with @JvmStatic :

class MyClass {
  companion object {
   @JvmStatic
    val SomeProperty = "hey"
  }
}

then go ahead and remove 'Companion' from your binding TextView:

Change from

 <TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="@{MyClass.Companion.SomeProperty}"/>

to

 <TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="@{MyClass.SomeProperty}"/>
1

TL;DR:

Replace

android:text="@{MyClass.Companion.SomeProperty}"

with

android:text="@{MyClass.Companion.getSomeProperty()}"

Explanation:

Your problem is that you're trying to reference the Kotlin object exactly as it is named but that's not how the Kotlin compiler will generate the property in Java. Instead, it will convert it using the Java convention of being a "get" function.

You can find out what this name will look like by decompiling the Kotlin Bytecode.

  1. Open the Kotlin class you want to see the bytecode for.
  2. Open Tools > Kotlin > Show Kotlin Bytecode
  3. In the side panel that opens up, click the Decompile button in the top-left.

This will show you the Java equalvalent of the Kotlin class, including the full name of the companion property.

Bonus:

That said, you probably would prefer to reference the field as a property, in which case you can just append the const keyboard to the property declaration.

const val SomeProperty = "hey"

With that the compiler will generate the field as a public static field, outside of the Companion, and you can update your xml to be simply:

android:text="@{MyClass.SomeProperty}"

Which is pretty much how you'd do it in Java.

Hope that helps!

1

There is another way: in class

const val SomeProperty = "hey"
class MyClass {}

in XML

  <data>
    <import type="package.MyClassKt"/>
  </data>

  <TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="@{MyClassKt.SomeProperty}"/>
0

I went through all of this answers and I had to come up with my own solution.

Mark the constant with const val modifiers (const is the key) and just import the "parent" class (MyClass in your case) and you don't need the word Companion

class MyClass {
  companion object {
    const val SomeProperty = "hey"
  }
}

XML

  <data>
    <import type="package.MyClass"/>
  </data>

  <TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="@{MyClass.SomeProperty}"/>

</layout>

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.