0

I'm starting to create graphical components on Android and I'm facing a problem that is I suppose very simple.

The attributes passed to my custom layout are read and well recognized in XML. However, I would like these attributes to be passed dynamically.

Here is my code:

    <declare-styleable name="MyAppBarLayout">
        <attr name="text" format="string" />
    </declare-styleable>
class MyAppBarLayout(context: Context, attrs: AttributeSet): AppBarLayout(context, attrs) {


    init {
        val view = inflate(context, R.layout.my_appbar, this)

        val attributes = context.obtainStyledAttributes(attrs, R.styleable.MyAppBarLayout)

        view.text_subtitle.text = attributes.getString(R.styleable.MyAppBarLayout_text)

        attributes.recycle()
    }

}

What I want to do with this view is this :

var myAppBar.text = "WARNING"

How can I set dynamic setters ? I have looked at Google's documentation on this subject, but I don't understand if I should have an attribute corresponding to the property.

mamenejr
  • 305
  • 9
  • 17

1 Answers1

1

One way of doing this is:

class MyAppBarLayout(context: Context, attrs: AttributeSet): AppBarLayout(context, attrs) {
    private var text: String? = null

    ...
    fun setText(text: String) {
        view.sutitle.text = text
    }
}

// wherever you want to set the text
var myAppBar.text = "WARNING"

The way you are doing is for setting the text(attribute) from layout xml.

Yang Liu
  • 1,300
  • 10
  • 14