Hoe voeg je aangepaste attributen toe voor een aangepaste view in Android?
sobes.tech AI
Antwoord van AI
-
Definitie van attributen in
attrs.xml: Er wordt een bestandres/values/attrs.xmlaangemaakt (of toegevoegd aan een bestaand bestand). Hierin wordt<declare-styleable>gedefinieerd met de naam van de aangepaste View en worden<attr>vermeld voor elk aangepaste attribuut, met vermelding van het formaat (format).<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="MyCustomView"> <attr name="customText" format="string"/> <attr name="customColor" format="color"/> <attr name="customEnabled" format="boolean"/> </declare-styleable> </resources> -
Gebruik van attributen in XML-layout: In de XML-layout waar de aangepaste View wordt gebruikt, worden specifieke attributen toegevoegd met de namespace
app.<com.example.MyCustomView android:layout_width="wrap_content" android:layout_height="wrap_content" xmlns:app="http://schemas.android.com/apk/res-auto" app:customText="Hallo Aangepaste View" app:customColor="@color/colorPrimary" app:customEnabled="true"/> -
Lezen van attributen in de View-code: In de constructor van de aangepaste View (meestal degene die
ContextenAttributeSetontvangt), worden de klassenTypedArrayenobtainStyledAttributesgebruikt om de waarden van de in XML gespecificeerde attributen te lezen.class MyCustomView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { // Variabelen voor het opslaan van de attribuutwaarden private var customText: String? = null private var customColor: Int = 0 private var customEnabled: Boolean = false init { // Verkrijgen van TypedArray met de attributen val typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView, defStyleAttr, 0) try { // Lezen van de attribuutwaarden customText = typedArray.getString(R.styleable.MyCustomView_customText) customColor = typedArray.getColor(R.styleable.MyCustomView_customColor, 0) // Standaardwaarde customEnabled = typedArray.getBoolean(R.styleable.MyCustomView_customEnabled, false) // Standaardwaarde // Nu kunnen customText, customColor en customEnabled worden gebruikt om de View te configureren // Bijvoorbeeld: // if (customEnabled) { /* ... */ } } finally { // Belangrijk! Resources vrijmaken door recycle() aan te roepen typedArray.recycle() } } // ... overige logica van de View ... }