Ответ
В Custom View можно добавить свои атрибуты через XML. Для этого:
- Создайте файл
attrs.xmlв папкеres/values/:
<resources>
<declare-styleable name="CustomView">
<attr name="customColor" format="color" />
<attr name="customText" format="string" />
<attr name="customSize" format="dimension" />
</declare-styleable>
</resources>
- В конструкторе View считайте атрибуты:
init {
context.theme.obtainStyledAttributes(
attrs,
R.styleable.CustomView,
0, 0
).apply {
try {
customColor = getColor(R.styleable.CustomView_customColor, Color.RED)
customText = getString(R.styleable.CustomView_customText) ?: ""
customSize = getDimension(R.styleable.CustomView_customSize, 16f)
} finally {
recycle()
}
}
}
- Используйте в XML:
<com.example.CustomView
app:customColor="@color/blue"
app:customText="Hello"
app:customSize="24sp" />
Не забудьте добавить пространство имен xmlns:app="http://schemas.android.com/apk/res-auto".