0

So I've got a custom view with this attribute:

    private var mLabelText: String = "DEFAULT"
    var labelText: String
        set(value) {
            if (mLabelText != value) {
                mLabelText = value
                invalidate()
            }
        }
        get() { return mLabelText }

And defined in attr.xml as

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

Now if I try to do this in my layout XML to set the value, it doesnt work (the text still shows 'DEFAULT')

        <CustomView
            ...
            app:text="NewText" />

However, if I do this, it works:

        <CustomView
            ...
            app:text="@{`NewText`}" />

So what gives? How come views like TextView allow me to do android:text="Text" instead of having to write android:text="@{`Text`}, but my own custom view wont?

Olli
  • 375
  • 5
  • 15
  • 1
    The second one is being handled by the data binding framework, which is generating code to set that for you when it detects the `@{}` value in processing that layout. The first setup is just a plain old attribute value, though, and the binding framework won't do anything with it, so unless you've handled that attribute in your custom `View`'s constructor, that property is not going to be set automatically. – Mike M. May 02 '22 at 19:44
  • 1
    I noticed that you referred to `var labelText` as an attribute, which might be where part of the confusion lies. That is not an attribute; that's just a regular Kotlin property. The attribute is defined only by the `` element, and is basically just the `app:labelText` entry in the XML. To wire that attribute up to your `var labelText` property, you'd have to read its value from the `AttributeSet` passed into the `View`'s constructor, like is shown in the last block in [this answer](https://stackoverflow.com/a/3441986) (it's in Java, but the Kotlin is basically the same). – Mike M. May 03 '22 at 05:08

1 Answers1

0

Mike's comments answer the confusion I had about the different syntaxes.

What I ended up doing ultimately is to inherit the existing android TextView. TextView has a bunch of stuff I needed like font, font size etc, so it was just simpler to inherit rather than re-implement it myself.

Olli
  • 375
  • 5
  • 15