Reputation: 17754
In Android, the mapping between attributes (like android:text
) and the corresponding data binding adapter is done by the binding adapter annotation containing the same attribute name (like @BindingAdapter("android:text")
).
So, if I want a data binding adapter from Double to String, do I have to use a custom attribute or is it possible to stick with android:text
and in addition specify something like android:useCustomBindingAdapter="my.double.to.string.bindingadapter"
?
Upvotes: 0
Views: 636
Reputation: 782
I think you can create static converting method and inverse adapter.
Create methods in some file/class, like
@file:JvmName("DoubleToStringConverter")
package com.test.android
fun doubleToString(view: EditText, num: Double) = num.toString()
@InverseMethod("doubleToString")
fun textToDouble(view: EditText, value: CharSequence): Double {
return value.toString().toDouble() }
and then in you layout
layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<import type="com.test.android.DoubleToStringConverter"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@={DoubleToStringConverter.doubleToString(your_viewmodel_live_data)}"
/>
</LinearLayout>
Upvotes: 1
Reputation: 1
If you want to bind a double add this code snippet:
@BindingAdapter("android:text")
fun bindToText(view: TextView, value: Double?) {
value?.let {
view.text = value.toString()
}
}
If you want to support multiple types:
@BindingAdapter("android:text")
fun bindToText(view: TextView, value: Any?) {
value?.let {
when (value) {
is Double -> view.text = String.format(Locale.getDefault(), "%.2f", value)
is Int -> view.text = value.toString()
}
}
}
Upvotes: 0