Junior — Middle
How can user attributes defined in XML be extracted within a custom View component?
sobes.tech AI
Answer from AI
To extract user attributes defined in XML within your custom View component in Android, you need to:
- Define the attributes in the
res/values/attrs.xmlfile:
<resources>
<declare-styleable name="MyCustomView">
<attr name="customAttr" format="string" />
<attr name="customColor" format="color" />
</declare-styleable>
</resources>
-
In the constructor of your custom View that takes
AttributeSet attrs, obtain aTypedArrayusing the methodcontext.obtainStyledAttributes(attrs, R.styleable.MyCustomView). -
Extract the needed attributes from the
TypedArray. -
Remember to call
recycle()on theTypedArrayafter use.
Example:
class MyCustomView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
var customText: String? = null
var customColor: Int = Color.BLACK
init {
attrs?.let {
val typedArray = context.obtainStyledAttributes(it, R.styleable.MyCustomView, 0, 0)
customText = typedArray.getString(R.styleable.MyCustomView_customAttr)
customColor = typedArray.getColor(R.styleable.MyCustomView_customColor, Color.BLACK)
typedArray.recycle()
}
}
}
Thus, you can use custom attributes defined in XML inside your component.