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 |