Sobes.tech
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, нужно:

  1. Определить атрибуты в файле res/values/attrs.xml:
<resources>
    <declare-styleable name="MyCustomView">
        <attr name="customAttr" format="string" />
        <attr name="customColor" format="color" />
    </declare-styleable>
</resources>
  1. В конструкторе вашего кастомного View, который принимает AttributeSet attrs, получить TypedArray с помощью метода context.obtainStyledAttributes(attrs, R.styleable.MyCustomView).

  2. Извлечь нужные атрибуты из TypedArray.

  3. Не забыть вызвать 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, внутри вашего компонента.