我试图在布局内使用伴随对象属性,但编译器无法识别它。
Kotlin 类
class MyClass {
companion object {
val SomeProperty = "hey"
}
}
XML布局
<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>
我得到了这个错误:
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)
...
我尝试过使用companion
代替Companion
,但没有运气。
是否可以通过数据绑定在 xml 布局上使用伴随对象?我该如何继续?预先感谢您的帮助:)
为了访问Companion
对象的属性和方法,就是NOT需要有一个 Parent 对象的实例。
伴生对象已经实例化,因此您可以直接访问实例。
而不是使用<import>
(这是 Java 的自然翻译),我们需要使用<variable>
,因为我们实际上想要将(已经实例化的)Companion 对象使用到我们的 XML 布局中。
按如下方式导入您的 Companion 对象
给定 Kotlin 类:
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
}
}
布局:
<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>
分段:
class MyFragment {
...
onViewCreated(...) {
// now bind the companion object to the variable declared in the XML
binding.myViewModelStatic = TransferUseCase.Companion
}
...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)