2

I have a custom view with a styleable attribute defined as:

<declare-styleable name="CustomView">
    <attr name="stringAttribute" format="string"/>
</declare-styleable>

I'd like to pass a string resource to this view when it is initialized, so I can grab it via obtainStyledAttributes and apply it to the view right away.

However, since the string resource is dynamic, I can't seem to find a way to pass it to the view without using a binding adapter.

Is it possible to pass a string resource ID to a custom view, without relying on a binding adapter?

The desired solution would be something like this (where the resource ID is dynamic):

app:stringAttribute="@{context.getString(R.string.value)}"

1 Answers1

3

Maybe I didn’t understand your question correctly, but you can configure the binding using the BindingAdapter. For example, you can set the string resource as follows:

TestBindings.kt

@BindingAdapter("stringRes")
fun setStringRes(view: TextView, @StringRes resource: Int) {
    view.text = view.context.getString(resource)
}

TestViewModel.kt

data class TestViewModel(@StringRes val text: Int)

test.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name="viewModel"
            type="... .TestViewModel" />
    </data>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        stringRes="@{viewModel.text}"/>

</layout>
Evgeny
  • 431
  • 3
  • 10
  • The question is specifically about a custom view string attribute. I'm already aware of how to use a binding adapter to update a view. As asked in the question, I'm trying to pass the resource ID to the view upon initialization. –  Feb 13 '20 at 04:08
  • Looks like this: https://stackoverflow.com/a/33175062/2170109. You can use `app:stringres="@{@string/mystring}"`. – hardysim Aug 13 '20 at 07:08