Search code examples
androidandroid-layoutkotlinandroid-databindingandroid-binding-adapter

How provide default value in BindingAdapter method in DataBinding Android


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?


Solution

  • 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
    }