首页 \ 问答 \ 如何解决:“实现与自定义视图的双向数据绑定时找不到属性'android:text'的getter?(How to solve: “cannot find getter for attribute 'android:text'” when implementing two-way data binding with custom view?)

如何解决:“实现与自定义视图的双向数据绑定时找不到属性'android:text'的getter?(How to solve: “cannot find getter for attribute 'android:text'” when implementing two-way data binding with custom view?)

我经历了许多类似的问题,但没有一个答案似乎解决了我的问题。 我实现了一个我想与双向数据绑定兼容的自定义EditText 。 问题是,每次我尝试编译时,我得到的错误:

Error:java.lang.IllegalStateException: failed to analyze: android.databinding.tool.util.LoggedErrorException: Found data binding errors.
****/ data binding error ****msg:Cannot find the getter for attribute 'android:text' with value type java.lang.String on com.app.toolkit.presentation.view.CustomEditText. file:/Users/humble-student/Home/workspace/android/application/app/src/main/res/layout/login_view.xml loc:68:8 - 81:69 ****\ data binding error ****

    at org.jetbrains.kotlin.analyzer.AnalysisResult.throwIfError(AnalysisResult.kt:57)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules(KotlinToJVMBytecodeCompiler.kt:137)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:158)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:61)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:107)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:51)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:92)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$2.invoke(CompileServiceImpl.kt:386)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$2.invoke(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:892)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.common.DummyProfiler.withMeasure(PerfUtils.kt:137)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.checkedCompile(CompileServiceImpl.kt:919)
    at 

这是我的实现:

CustomEditText

class CustomEditText @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {

    // ...
    private lateinit var editText_input: EditText
    private lateinit var textView_errorMessage: TextView

    private var isErrorDisplayed = false
    private var inputTextOriginalColor: ColorStateList? = null

    init {
        orientation = VERTICAL
        clearContainerFormatting()

        createEditTextInput(context, attrs, defStyleAttr)
        createTextViewErrorMessage(context)

        addView(editText_input)
        addView(textView_errorMessage)
    }

    fun setError(message: String) {
        //...
    }

    fun getText(): String = editText_input.text.toString()

    fun setText(text: String) = editText_input.setText(text)

    // ...
}

模型

data class SampleData(
        private var _content: String
) : BaseObservable() {
    var content: String
        @Bindable get() = _content
        set(value) {
            _content = value
            notifyPropertyChanged(BR.content)
        }
}

使用CustomView和数据绑定的客户端

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

<layout 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">

    <data>

        <import type="android.view.View" />

        <variable
            name="data"
            type="SampleData" />

        <variable
            name="presenter"
            type="SamplePresenter" />
    </data>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:animateLayoutChanges="true"
        tools:context=".sample_view.presentation.view.SampleView">

        <NotificationPopup
            android:id="@+id/notificationPopup"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clipToPadding="false"
            android:elevation="4dp"
            app:allowManualExit="true" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:id="@+id/textView_mirror"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif"
                android:text="@{data.content}"
                android:textSize="16sp"
                android:textStyle="bold"
                tools:text="test" />

            <CustomEditText
                android:id="@+id/customEditText_sample"
                style="@style/RegisterInput"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Type anything"
                android:text="@={data.content}" />

            <Button
                android:id="@+id/button_validateInput"
                style="@style/Widget.AppCompat.Button.Colored"
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:layout_marginEnd="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:onClick='@{(v) -> presenter.onValidateDataClick(customEditTextSample.getText())}'
                android:text="Validate Input" />
        </LinearLayout>
    </RelativeLayout>
</layout>

PS:如果我替换常规EditText小部件的CustomEditText ,它可以很好地工作


I went through many kinda-similar questions but none of the answers seemed to solve my problem. I implemented a custom EditText that I want to be compatible with two-way data binding. The problem is, every time I try to compile I get the error:

Error:java.lang.IllegalStateException: failed to analyze: android.databinding.tool.util.LoggedErrorException: Found data binding errors.
****/ data binding error ****msg:Cannot find the getter for attribute 'android:text' with value type java.lang.String on com.app.toolkit.presentation.view.CustomEditText. file:/Users/humble-student/Home/workspace/android/application/app/src/main/res/layout/login_view.xml loc:68:8 - 81:69 ****\ data binding error ****

    at org.jetbrains.kotlin.analyzer.AnalysisResult.throwIfError(AnalysisResult.kt:57)
    at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules(KotlinToJVMBytecodeCompiler.kt:137)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:158)
    at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:61)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:107)
    at org.jetbrains.kotlin.cli.common.CLICompiler.execImpl(CLICompiler.java:51)
    at org.jetbrains.kotlin.cli.common.CLITool.exec(CLITool.kt:92)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$2.invoke(CompileServiceImpl.kt:386)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$2.invoke(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:892)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$$inlined$ifAlive$lambda$2.invoke(CompileServiceImpl.kt:96)
    at org.jetbrains.kotlin.daemon.common.DummyProfiler.withMeasure(PerfUtils.kt:137)
    at org.jetbrains.kotlin.daemon.CompileServiceImpl.checkedCompile(CompileServiceImpl.kt:919)
    at 

Here is my implementation:

CustomEditText

class CustomEditText @JvmOverloads constructor(
        context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {

    // ...
    private lateinit var editText_input: EditText
    private lateinit var textView_errorMessage: TextView

    private var isErrorDisplayed = false
    private var inputTextOriginalColor: ColorStateList? = null

    init {
        orientation = VERTICAL
        clearContainerFormatting()

        createEditTextInput(context, attrs, defStyleAttr)
        createTextViewErrorMessage(context)

        addView(editText_input)
        addView(textView_errorMessage)
    }

    fun setError(message: String) {
        //...
    }

    fun getText(): String = editText_input.text.toString()

    fun setText(text: String) = editText_input.setText(text)

    // ...
}

Model

data class SampleData(
        private var _content: String
) : BaseObservable() {
    var content: String
        @Bindable get() = _content
        set(value) {
            _content = value
            notifyPropertyChanged(BR.content)
        }
}

Client that uses the CustomView with data binding

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

<layout 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">

    <data>

        <import type="android.view.View" />

        <variable
            name="data"
            type="SampleData" />

        <variable
            name="presenter"
            type="SamplePresenter" />
    </data>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:animateLayoutChanges="true"
        tools:context=".sample_view.presentation.view.SampleView">

        <NotificationPopup
            android:id="@+id/notificationPopup"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:clipToPadding="false"
            android:elevation="4dp"
            app:allowManualExit="true" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:id="@+id/textView_mirror"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif"
                android:text="@{data.content}"
                android:textSize="16sp"
                android:textStyle="bold"
                tools:text="test" />

            <CustomEditText
                android:id="@+id/customEditText_sample"
                style="@style/RegisterInput"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Type anything"
                android:text="@={data.content}" />

            <Button
                android:id="@+id/button_validateInput"
                style="@style/Widget.AppCompat.Button.Colored"
                android:layout_width="150dp"
                android:layout_height="wrap_content"
                android:layout_marginEnd="8dp"
                android:layout_marginStart="8dp"
                android:layout_marginTop="8dp"
                android:onClick='@{(v) -> presenter.onValidateDataClick(customEditTextSample.getText())}'
                android:text="Validate Input" />
        </LinearLayout>
    </RelativeLayout>
</layout>

P.S.: If I replace CustomEditText for regular EditText widget, it works perfectly


原文:https://stackoverflow.com/questions/47849808
更新时间:2022-07-16 20:07

最满意答案

已经发布了一些好的答案,但他们没有深入到问题的核心:所有其他的事情都是平等的,如果你可以实现某种东西作为一个免费的,非朋友的功能,你应该总是这样做。

为什么?

因为免费的非朋友功能,没有特权访问状态。 测试类比测试函数要困难得多,因为您必须说服自己,无论调用哪个成员函数,甚至是成员函数的组合,都可以维护类的不变量。 您拥有的会员/朋友功能越多,您需要做的工作就越多。

免费功能可以独立推理和测试。 因为他们没有特权访问类的状态,所以他们不可能违反任何类的不变式。

我不知道什么是不变量以及什么特权访问path允许的细节,但显然他们能够将许多功能实现为免费功能,并且他们做出了正确的选择并做到了这一点。

Scott Meyers关于这个话题的精彩文章 ,给出了是否使某个功能成为会员的“算法”。

Herb Sutter叹息std::string的大量接口 。 为什么? 因为,大部分string的接口都可以作为自由函数来实现。 偶尔使用它可能会更加笨拙,但它更容易测试,推理,改进封装和模块化,为以前没有的代码重用开启机会等等。


There are a couple of good answers already posted, but they do not get to the heart of the matter: all other things being equal, if you can implement something as a free, non-friend function, you always should.

Why?

Because, free, non-friend functions, do not have privileged access to state. Testing classes is much harder than testing functions because you have to convince yourself that the class' invariants are maintained no matter which members functions are called, or even combinations of member functions. The more member/friend functions you have, the more work you have to do.

Free functions can be reasoned about and tested standalone. Because they don't have privileged access to class state, they cannot possibly violate any class invariants.

I don't know the details of what invariants and what privileged access path allows, but obviously they were able to implement a lot of functionality as free functions, and they make the right choice and did so.

Scott Meyers brilliant article on this topic, giving the "algorithm" for whether to make a function a member or not.

Here's Herb Sutter bemoaning the massive interface of std::string. Why? Because, much of string's interface could have been implemented as free functions. It may be a bit more unwieldy to use on occasion, but it's easier to test, reason about, improves encapsulation and modularity, opens opportunities up for code reuse that were not there before, etc.

相关问答

更多

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。