Как задать свои атрибуты в Custom View

«Как задать свои атрибуты в Custom View» — вопрос из категории UI и Views, который задают на 23% собеседований Android Разработчик. Ниже — развёрнутый ответ с разбором ключевых моментов.

Ответ

В Custom View можно добавить свои атрибуты через XML. Для этого:

  1. Создайте файл 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>
  1. В конструкторе 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()
        }
    }
}
  1. Используйте в XML:
<com.example.CustomView
    app:customColor="@color/blue"
    app:customText="Hello"
    app:customSize="24sp" />

Не забудьте добавить пространство имен xmlns:app="http://schemas.android.com/apk/res-auto".