Ответ
В Custom View кастомные атрибуты объявляются в res/values/attrs.xml. Для их получения в коде:
- Объявляем атрибуты:
<declare-styleable name="CustomView">
<attr name="customColor" format="color"/>
<attr name="customText" format="string"/>
</declare-styleable>
- В конструкторе View получаем значения:
init {
context.theme.obtainStyledAttributes(
attrs,
R.styleable.CustomView,
0, 0
).apply {
try {
val color = getColor(R.styleable.CustomView_customColor, Color.BLACK)
val text = getString(R.styleable.CustomView_customText) ?: ""
// Применяем атрибуты
} finally {
recycle()
}
}
}
Ключевые моменты:
- Всегда вызывайте
recycle()после использования TypedArray - Указывайте дефолтные значения в get-методах
- Префикс стиля (CustomView_) добавляется автоматически