Junior — Middle
92
Cum se pot extrage atributele utilizator definite în XML în interiorul propriului component View?
Companiile au fost întrebate
NetUP
Răspuns de la AI
sobes.tech AI
Для извлечения пользовательских атрибутов, определённых в XML, внутри собственного компонента View в Android, нужно:
- Определить атрибуты в файле
res/values/attrs.xml:
<resources>
<declare-styleable name="MyCustomView">
<attr name="customAttr" format="string" />
<attr name="customColor" format="color" />
</declare-styleable>
</resources>
-
В конструкторе вашего кастомного View, который принимает
AttributeSet attrs, получитьTypedArrayс помощью методаcontext.obtainStyledAttributes(attrs, R.styleable.MyCustomView). -
Извлечь нужные атрибуты из
TypedArray. -
Не забыть вызвать
recycle()уTypedArrayпосле использования.
Пример:
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()
}
}
}
Таким образом, вы можете использовать пользовательские атрибуты, заданные в XML, внутри вашего компонента.