How to add custom attributes to a custom view in Android?
sobes.tech AI
Answer from AI
-
Defining attributes in
attrs.xml: Create a fileres/values/attrs.xml(or add to an existing one). In it, define<declare-styleable>with the name of the custom View and list<attr>for each custom attribute, specifying their format (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> -
Using attributes in XML layout: In the XML layout where the custom View is used, add the specified attributes using the
appnamespace.<com.example.MyCustomView android:layout_width="wrap_content" android:layout_height="wrap_content" xmlns:app="http://schemas.android.com/apk/res-auto" app:customText="Hello Custom View" app:customColor="@color/colorPrimary" app:customEnabled="true"/> -
Reading attributes in View code: In the constructor of the custom View (usually the one that takes
ContextandAttributeSet), useTypedArrayandobtainStyledAttributesto read the attribute values specified in XML.class MyCustomView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : View(context, attrs, defStyleAttr) { // Variables to store attribute values private var customText: String? = null private var customColor: Int = 0 private var customEnabled: Boolean = false init { // Obtain TypedArray with attributes val typedArray = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView, defStyleAttr, 0) try { // Read attribute values customText = typedArray.getString(R.styleable.MyCustomView_customText) customColor = typedArray.getColor(R.styleable.MyCustomView_customColor, 0) // Default value added customEnabled = typedArray.getBoolean(R.styleable.MyCustomView_customEnabled, false) // Default value added // Now you can use customText, customColor, and customEnabled to configure the View // For example: // if (customEnabled) { /* ... */ } } finally { // Important! Recycle TypedArray to free resources typedArray.recycle() } } // ... rest of the View logic ... }The
obtainStyledAttributesmethod returns aTypedArray, from which attribute values can be extracted by their indices (generated by the R class). After use, callrecycle()to free resources.