해결 방법 : 사용자 정의보기로 양방향 데이터 바인딩을 구현할 때 " 'android : text'속성에 대한 getter를 찾을 수 없습니다."

겸손한 학생

나는 비슷한 질문을 많이했지만 답이 내 문제를 해결하지 못하는 것 같았습니다. 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>

추신 : CustomEditText일반 EditText위젯으로 교체하면 완벽하게 작동합니다.

겸손한 학생

재미 있었지만 이 문제를 해결하는 데 도움이 되는 매체에 대한 훌륭한 게시물 을 찾을 수있었습니다 . 기본적으로 필요한 것은 다음과 CustomEditTextBinder같습니다.

@InverseBindingMethods(
        InverseBindingMethod(
                type = CustomEditText::class,
                attribute = "android:text",
                method = "getText"
        )
)
class CustomEditTextBinder {
    companion object {
        @JvmStatic
        @BindingAdapter(value = ["android:textAttrChanged"])
        fun setListener(editText: CustomEditText, listener: InverseBindingListener?) {
            if (listener != null) {
                editText.addTextChangedListener(object : TextWatcher {
                    override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {

                    }

                    override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {

                    }

                    override fun afterTextChanged(editable: Editable) {
                        listener.onChange()
                    }
                })
            }
        }

        @JvmStatic
        @BindingAdapter("android:text")
        fun setText(editText: CustomEditText, text: String?) {
            text?.let {
                 if (it != editText.text) {
                     editText.text = it
                 }
            }
         }

이상하게 보일 수 있지만 실제로는 아무데도 호출 할 필요가 없습니다. 클래스를 추가하기 만하면 프레임 워크가 주석 처리를 통해 찾을 수 있습니다. (가) 있습니다 setText무한 루프를 방지하기 위해 정말 중요하다. 또한 다음을 추가했습니다.

var text: String?
    get() = editText_input.text.toString()
    set(value) {
        editText_input.setText(value)
    }

fun addTextChangedListener(listener: TextWatcher) =
        editText_input.addTextChangedListener(listener)

CustomEditText.

다음은 구현예입니다.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

TOP 리스트

  1. 1

    Matlab의 반복 Sortino 비율

  2. 2

    ImageJ-히스토그램 빈을 변경할 때 최대, 최소 값이 변경되는 이유는 무엇입니까?

  3. 3

    Excel : 합계가 N보다 크거나 같은 상위 값 찾기

  4. 4

    C #에서 'System.DBNull'형식의 개체를 'System.String'형식으로 캐스팅 할 수 없습니다.

  5. 5

    원-사각형 충돌의 충돌 측면을 찾는 문제

  6. 6

    Oracle VirtualBox-설치를 위해 게스트를 부팅 할 때 호스트 시스템이 충돌 함

  7. 7

    어떻게 아무리 "나쁜", ANY의 SSL 인증서와 HttpClient를 사용하지합니다

  8. 8

    Ubuntu는 GUI에서 암호로 사용자를 만듭니다.

  9. 9

    잘못된 상태 예외를 발생시키는 Apache PoolingHttpClientConnectionManager

  10. 10

    Python 사전을 사용하는 동안 "ValueError : could not convert string to float :"발생

  11. 11

    openCV python을 사용하여 텍스트 문서에서 워터 마크를 제거하는 방법은 무엇입니까?

  12. 12

    Vuetify 다중 선택 구성 요소에서 클릭 한 항목의 값 가져 오기

  13. 13

    C ++ VSCode에서 같은 줄에 중괄호 서식 지정

  14. 14

    Cassandra에서 버전이 지정된 계층의 효율적인 모델링

  15. 15

    JQuery datepicker 기능이 인식되지 않거나 새 프로젝트에서 작동하지 않음

  16. 16

    cuda 11.1에서 Pytorch를 사용할 때 PyTorch가 작동하지 않음: Dataloader

  17. 17

    jfreecharts에서 x 및 y 축 선을 조정하는 방법

  18. 18

    상황에 맞는 메뉴 색상

  19. 19

    마우스 휠 JQuery 이벤트 핸들러에 대한 방향 가져 오기

  20. 20

    매개 변수에서 쿼리 객체를 선언하는 방법은 무엇입니까?

  21. 21

    Maven은 아이 프로젝트 대상 폴더를 청소하지

뜨겁다태그

보관