Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 694
Samuel Robert Avatar asked Jun 08 '18 07:06

Samuel Robert


People also ask

How do I use BindingAdapter on Android?

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.

What is @BindingAdapter?

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.

What is inverse binding adapter in Android?

android.databinding.InverseBindingAdapter. InverseBindingAdapter is associated with a method used to retrieve the value for a View when setting values gathered from the View.


1 Answers

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
}
like image 130
Mário Augusto Avatar answered Sep 28 '22 12:09

Mário Augusto