I have a custom button with some stylable attributes
<declare-styleable name="MBButton">
<attr name="button_type_accessible" format="enum">
<enum name="primary" value="0" />
<enum name="secondary" value="1" />
<enum name="secondary_alternative" value="2" />
<enum name="ghost" value="3" />
<enum name="ghost_alternative" value="4" />
<enum name="action" value="5" />
</attr>
<attr name="is_medium_size_accessible" format="boolean" />
<attr name="is_small_size_accessible" format="boolean" />
<attr name="make_accessible_button" format="string" />
</declare-styleable>
I need to create this button programmatically and set some of this attributes. I guess to do this I should set this info in the AttributeSet and use it when I create the button. But I cannot make it work in Kotlin.
This is the constructor of my custom button
class CustomButton @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = R.attr.mbButtonSecondaryStyle
)
CodePudding user response:
You can make functions in your CustomButton
class as follow
class CustomButton @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int =
R.attr.mbButtonSecondaryStyle
) {
init{
...
}
fun setAccessibleButton(text: String) {
binding.textView.text.setText(text)
}
}
Suppose you create function for make_accessible_button
as follow:
Do this same for each attribute and code the functionality as you want.
CodePudding user response:
according to https://developer.android.com/develop/ui/views/layout/custom-views/create-view#addprop you can't programmatically set attrs,but instead you should define filds/getters/setters for your attrs.