动态设置器自定义视图

问题描述 投票:0回答:1

我开始在Android上创建图形组件,并且遇到了我认为非常简单的问题。

传递到我的自定义布局的属性已在XML中读取并很好地识别。但是,我希望这些属性可以动态传递。

这是我的代码:

    <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()
    }

}

我想用这个视图做的是这个:

var myAppBar.text = "WARNING"

如何设置动态设置器?我看过Google关于此主题的文档,但不知道是否应具有与该属性对应的属性。

android kotlin android-custom-view
1个回答
1
投票

一种方法是:

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"

您正在做的是从布局xml设置文本(属性)。

© www.soinside.com 2019 - 2024. All rights reserved.