I'm working on a binding adapter method to set color span in TextView
.
@BindingAdapter("foregroundColorSpan", "start", "end", requireAll = false)
fun TextView.setForegroundColorSpan(color: Int, start: Int = 0, end: Int = text.length - 1) {
val spanBuilder = SpannableStringBuilder(text)
spanBuilder.setSpan(ForegroundColorSpan(color), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
text = spanBuilder
}
Here is how I'm using this
<TextView
android:id="@+id/loginLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="@dimen/narrow"
android:text="@string/already_have_account_login"
android:textColor="@color/grey_aee4e4e4"
android:textSize="@dimen/text_size_small"
app:foregroundColorSpan="@{@color/blue_ae12235b}"
app:start="@{25}" />
I can't seem to get the end
as parameter default that is specified as last index of the text in TextView
Is there any work around I could use to get the default value from the parameter without having to check if the value is 0?
To create a custom binding adapter, you need to create an extension function of the view that will use the adapter. Then, you add the @BindingAdapter annotation. You have to indicate the name of the view attribute that will execute this adapter as a parameter in the annotation.
A static binding adapter method with the BindingAdapter annotation allows you to customize how a setter for an attribute is called. The attributes of the Android framework classes already have BindingAdapter annotations created.
android.databinding.InverseBindingAdapter. InverseBindingAdapter is associated with a method used to retrieve the value for a View when setting values gathered from the View.
No default value is respected in bindingAdapters. The generated class is in Java and if the requireAll is set to false, everything that is not programatically set will be null, false (in case of booleans) or 0 (for numbers). So in order to work your BindingAdapter function should be like:
@BindingAdapter(
value = ["foregroundColorSpan", "start", "end"],
requireAll = false
)
fun TextView.setForegroundColorSpan(color: Int, start: Int?, end: Int?) {
val startValue = start ?: 0
val endValue = end ?: text.length - 1
val spanBuilder = SpannableStringBuilder(text)
spanBuilder.setSpan(ForegroundColorSpan(color), startValue, endValue, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
text = spanBuilder
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With