• 목록 (128)
    • Android (62)
    • Back-End (2)
    • Java (3)
    • Kotlin (16)
    • CS (7)
    • 개발 서적 (12)
    • 문제 풀이 (26)

최근 글

티스토리

전체 방문자
오늘
어제
hELLO · Designed By 정상우.
MJ_94
Android

[Android] two-way binding 형식 지정하기

[Android] two-way binding 형식 지정하기
Android

[Android] two-way binding 형식 지정하기

2022. 7. 6. 15:11

EditText에 데이터 바인딩을 적용하면서 입력되는 문자를 특정 형식으로 바로 변환해주고 싶었다.

해서 Converter라는 Object 클래스를 만들고 아래와 같은 함수를 만들었다.

object Converter{
    @JvmStatic
    fun stringWithFormat(
        value: String?
    ): String {
        return value?.moneyFormat() ?: ""
    }
}


위 함수를 EditText의 속성에 databinding으로 적용해 보았다.

<androidx.appcompat.widget.AppCompatEditText
    android:id="@+id/edit_loan_amount"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:background="@null"
    android:gravity="end"
    android:hint="@string/common_zero"
    android:inputType="number"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:text="@={Converter.stringWithFormat(vm.amount)}"
    android:textColor="@color/black"
    android:textSize="18dp"
    android:textStyle="bold"
    tools:text="0" />

 

실행 결과는 에러이고 그 이유는 아래와 같다.

The expression 'yourpackage.util.Converter.stringWithFormat(vmAmountGetValue)' cannot be inverted, so it cannot be used in a two-way binding

Details: There is no inverse for method stringWithFormat, you must add an @InverseMethod annotation to the method to indicate which method should be used when using it in two-way binding expressions

메시지에서 알 수 있듯이 양방향 바인딩 표현식에선 해당 메소드의 InverseMethod도 함께 만들어야 적용할 수 있다.
그러므로 작성한 메소드와 상반된 메소드를 만들고 @InverseMethod 어노테션으로 지정해주자.

object Converter{
    @InverseMethod("stringWithFormat")
    @JvmStatic fun stringNoFormat(
        value: String?
    ): String {
        return value?.removeFormat() ?: ""
    }

    @JvmStatic
    fun stringWithFormat(
        value: String?
    ): String {
        return value?.moneyFormat() ?: ""
    }
}
저작자표시 비영리 변경금지 (새창열림)

'Android' 카테고리의 다른 글

[Android] Vector 이미지  (0) 2022.11.24
[Android] left, top, right, bottom  (0) 2022.11.15
[Android] Android Architecture Components(AAC)  (0) 2022.04.27
[Android] Retrofit2  (0) 2022.04.07
[Android] Shape에 margin 속성 추가하기  (0) 2022.04.05
    'Android' 카테고리의 다른 글
    • [Android] Vector 이미지
    • [Android] left, top, right, bottom
    • [Android] Android Architecture Components(AAC)
    • [Android] Retrofit2
    MJ_94
    MJ_94
    안드로이드, 개발 관련 기술 블로그

    티스토리툴바

    단축키

    내 블로그

    내 블로그 - 관리자 홈 전환
    Q
    Q
    새 글 쓰기
    W
    W

    블로그 게시글

    글 수정 (권한 있는 경우)
    E
    E
    댓글 영역으로 이동
    C
    C

    모든 영역

    이 페이지의 URL 복사
    S
    S
    맨 위로 이동
    T
    T
    티스토리 홈 이동
    H
    H
    단축키 안내
    Shift + /
    ⇧ + /

    * 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.