Search code examples
androidkotlinandroid-databindingandroidxandroid-binding-adapter

Using a BindingAdapter with a string-array in Kotlin


I have the following BindingAdapter:

@BindingAdapter("entries")
fun setEntries(view: Spinner, entries: Array<String>) {
    // Do something
}

And on my XML file:

<Spinner
    android:id="@+id/spinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:entries="@{@stringArray/my_string_array}"/>

But when building, I get an error:

e: [kapt] An exception occurred: android.databinding.tool.util.LoggedErrorException: Found data binding errors.
****/ data binding error ****msg:Cannot find the setter for attribute 'app:entries' with parameter type java.lang.String[] on android.widget.Spinner.

I have followed the advice in this question, but what would be the Kotlin equivalent for String[] in this case?

Or, alternatively, can I pass the actual resource id instead of a String array to the Binding Adapter?

Thank you!


Solution

  • Well, the error won't be reproduced with the code provided, because it was in the second parameter, which I omitted naively thinking it was unrelated to the problem.

    The actual code was:

    @BindingAdapter("entries", "hint", requireAll = false)
    fun setHintAdapter(view: Spinner, entries: Array<String>, @StringRes hintRes: Int?) {
    
        val hint = hintRes?.run {
            try {
                MainAct.i.getString(this)
            } catch (e: Resources.NotFoundException) {
                null
            }
        } ?: ""
    
        val layout = android.R.layout.simple_spinner_item
    
        view.adapter = HintAdapter(hint, view.context, layout, entries)
    }
    

    And the XML:

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:entries="@{@stringArray/my_string_array}"
        app:hint="@{@string/some_string}"/>
    

    The error is completely unrelated to app:entries, it's in app:hint. I'm providing a String and expecting an Int (Well, a StringRes).

    Changing it to:

    @BindingAdapter("entries", "hint", requireAll = false)
    fun setHintAdapter(view: Spinner, entries: Array<String>, hint: String) {
    
        val layout = android.R.layout.simple_spinner_item
    
        view.adapter = HintAdapter(hint, view.context, layout, entries)
    }
    

    Fixes it.